The briefest series to equate a mathematical expression with a specific target value

While studying eloquent JavaScript, I encountered a program that checks whether any combination of multiplying 3 and adding 5 produces the target value:

However, this function does not provide the shortest possible sequence for achieving the target value.

I am struggling to figure out the logic needed to obtain the shortest possible solution. How can I modify this code to generate the shortest path?

function find_solution(target) {
  function find(current, history) {
    if (target === current) {
      return history;
    } else if (target < current) {
      return null;
    } else {
      return find(current + 5, `(${history} + 5)`) || find(current * 3, `(${history} * 3)`);
    }
  }
  return find(1, '1');
}

console.log(find_solution(24));

Answer №1

Nice attempt! While you're currently implementing a DFS, it's important to note that DFS does not always provide the shortest path. Consider utilizing a BFS approach as an initial option for finding the shortest path. Optimal adjustments may be required.

function findShortestPath(target, start = 1, addend = 5, multiplier = 3) {
  const visitedNodes = new Set();
  
  for (const queue = [[start, start]]; queue.length;) {
    const [path, current] = queue.shift();
    
    if (visitedNodes.has(current)) continue;
    
    visitedNodes.add(current);

    if (current === target) {
      return `${path} = ${target}`;
    }
    else if (current < target) {
      queue.push(...[[`(${path} + ${addend})`, current + addend],
                     [`(${path} * ${multiplier})`, current * multiplier]]);
    }
  }
};

console.log(findShortestPath(24));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the auto-import feature in the new VSCODE 1.18 compatible with nodelibs installed via npm?

Testing out the latest auto-import feature using a JS file in a basic project. After npm installing mongoose and saving an empty JS file for editing, I anticipate that typing const Schema = mongoose. will trigger an intellisense menu with mongoose nodelib ...

Is there a method to determine the height of the viewport if the DOCTYPE is not specified in Chrome, Firefox, or Safari?

How can we accurately determine the viewport's height even if the DOCTYPE is not specified? When the DOCTYPE is missing, values that would typically be around 410 may instead show as 3016. Is there a solution for finding the viewport's height wi ...

The button component in my React application is not functioning as expected, despite utilizing the useState and useEffect hooks

I'm having trouble with my Button not working, even though I am using useState and useEffect Check out the code below: import React, { useState, useEffect } from "react"; // import Timeout from "await-timeout"; import ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

Discover a specific segment of the pie chart

Currently, I have a pie chart that has been created using HTML5 canvas. I am able to retrieve the coordinates (X,Y) when the mouse hovers over it. Now, my goal is to determine which slice of the pie chart the Point (X,Y) falls into. Please note: I have ...

Translate a portion of a painting by utilizing context.putImageData()

I am attempting to gradually fill a canvas with pieces of the original image. To achieve this, I need each square of the image to be filled in iteratively on the canvas. To optimize performance, my approach involves rendering the original image onto an of ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

What could be causing my React button to stop functioning as a link to an external website when using anchor tags?

I recently created some buttons for my website using React. Initially, everything was working perfectly with the buttons, but suddenly they stopped functioning. Strangely, I didn't make any alterations to the code and I'm puzzled as to why they a ...

Preventing preventDefault() from firing in JQuery only when necessary

I have come up with a script that I recently created. <script> $(document).ready(function(){ $('a').data('loop',true); $('body').on('click', 'a', function(event){ console.lo ...

Looking for the final entry in a table using AngularJS

Hey everyone, I'm dealing with a table row situation here <tbody> <tr *ngFor="let data of List | paginate : { itemsPerPage: 10, currentPage: p }; let i = index"> <td>{{ d ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

Navigating through search results on an XML page using jQuery

Context: I am currently facing a challenge involving the integration of Google search outcomes into a webpage I'm constructing. These findings are presented in XML format. My current approach to importing the XML is as follows: if (window.XMLHttpReq ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...

Web page containing information from IPv6 and IPv4 sources exclusively

Is it possible to have an HTML5 page accessible through both IPv4 and IPv6, while only allowing CSS style and JavaScript from other domains via IPv4? Unfortunately, it seems that this setup does not function properly for pure IPv6 connections. Will th ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Enhance Vue functionality by adding a versatile mutation that can be utilized across

I am facing a challenge where I have a mutation that needs to be reused in multiple Vuex modules but should only modify the state at each module level. Is there a way to separate out this mutation so it can be easily added to each module's mutations w ...

Monitoring Object Changes in Angular 4

ETA: I am aware of different methods for monitoring my form for alterations. However, that is not the focus of my inquiry. As indicated by the title, my question pertains to observing changes within an object. The application displayed below is solely for ...

Guide: Using jQueryUI's explode effect to animate an HTML element explosion

I'm having trouble getting the jQueryUI explode effect to work properly. I've tested it out on this jsfiddle, but the explosion effect doesn't seem to happen as expected - the element just disappears with no explosion animation. $('h1, ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...