Home > Article > Web Front-end > How Does Recursion Operate in the \"FindSequence\" Function?
Eloquent Javascript introduces a challenging problem: writing a function that generates a sequence of additions and multiplications to reach a given goal number. The provided code employs recursion, which raises questions about its operation.
Within the findSequence function resides a nested function find. This function recursively explores two possible transformations from a current number: adding 5 or multiplying by 3. Each transformation produces a new number, and the process continues until either the goal is met or the current number exceeds the goal.
At each step, a textual representation of the expression is passed along. For instance, starting with the number 1, the initial expression is "1". If adding 5 is chosen, the expression becomes "(1 5)". By recording these expressions, the function tracks the steps taken to reach each number.
If the goal is reached, the expression from the final step represents a valid sequence. Otherwise, the function returns null, indicating failure. Multiple recursive calls are made, each exploring a different path until a valid sequence is found or all paths have been exhausted.
To illustrate the recursion, let's consider finding a sequence for the goal number 14.
(1, "1") (5, "1 + 5") (10, "(1 + 5) + 5") (15, "((1 + 5) + 5) + 5") // Discard, exceeds goal (30, "((1 + 5) + 5) * 3") // Discard, exceeds goal (15, "(1 + 5) * 3") // Discard, exceeds goal (3, "1 * 3") (8, "(1 * 3) + 5") (13, "((1 * 3) + 5) + 5") (18, "(((1 * 3) + 5) + 5) + 5") // Discard, exceeds goal (39, "(((1 * 3) + 5) + 5) * 3") // Discard, exceeds goal (24, "((1 * 3) + 5) * 3") // Discard, exceeds goal (9, "(1 * 3) * 3") (14, "((1 * 3) * 3) + 5") // Success!
Through this stepwise process of recursion, the function eventually finds the sequence: "((1 3) 3) 5", which represents the addition of 5 to the product of 1 and 3 cubed.
The above is the detailed content of How Does Recursion Operate in the \"FindSequence\" Function?. For more information, please follow other related articles on the PHP Chinese website!