I was reading Eloquent JavaScript and I came across this example for the puzzle:
Consider this puzzle: By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a number, tries to find a sequence of additions and multiplications that produce that number?
Here’s the code for the solution:
function findSequence(goal) { function find(start, history) { if (start == goal) return history; else if (start > goal) return null; else return find(start + 5, '(' + history + ' + 5)') || find(start * 3, '(' + history + ' * 3)'); } return find(1, '1'); } print(findSequence(24));
Could someone clear up how dod find get executed if it didn’t have a value for the arguments start and goal? Also how did the recursion happen?
But
finddidn’t get executed without a value forstartandgoal. It was first executed with the value1forstart, and the only value forgoalwas24.Perhaps you’re confused about the order of operations. There we see the declaration of a function,
findSequence. During the declaration, no code is executed. ThefindSequencefunction only gets executed later, on the last line, where the result of executing the function gets printed out.Within the declaration of
findSequence, there’s a declaration of another function,find. Once again, it doesn’t get executed until later. ThefindSequencefunction has just one executable line of code, the one that callsfind(1, '1'). Execution of that one line triggers the execution offindsome number of times, recursively. Thefindfunction makes reference togoal; when the Javascript interpreter executes the code,goalalways refers to the parameter offindSequence, and since in this examplefindSequenceis only called once,goalalways has the same value,24.You should be able to see where the recursion happened. If
startwas equal togoal, then the function stops; it returns the history of how it arrived at that number. Ifstartis greater thangoal, then it returnsnull, indicating that that path was not a path to the target number. Ifstartis still less thangoal, then the function tries calling itself with its start value plus 5. If that returns a non-null value, then that’s what gets returned. Otherwise, it tries multiplying by 3 and returning that history value instead.Note that although this code can return many numbers, it cannot return all numbers. If the goal is
2, for example,findSequencewill returnnullbecause there is no way to start at1and get to2by adding5or multiplying by3.