Question

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");
}

findSequence(24);

This is from Eloquent JavaScript. The purpose of it is "given a number, tries to find a sequence of additions and multiplications that produce that number".

I've run the debugger in Chrome and I get this stack on the start variable when running the function with the number 24. I am trying to specifically understand the start variable as it changes.

  1. start = 1 - Add 5.
  2. start = 6 - Add 5.
  3. start = 11 - Add 5.
  4. start = 16 - Add 5.
  5. start = 21 - Add 5.
  6. start = 26. Greater than 24. Return null. Start returns to 21. Try multiplying by 3.
  7. start = 63. Greater than 24. Return null. Start returns to 21.

It is at this point, that start changes from 21 to 16. Why is this? I don't see anything in the code that would bring it back down. It repeats this for 16, multiplying it by 3, going back to 16, and then going back down to 11. I'd really like to know what is going on here.

Was it helpful?

Solution

1
+ 5 -- 6
       + 5 -- 11
               + 5 -- 16
                       + 5 -- 21
                               + 5 -- 26 > 24, returns null
                               x 3 -- 63 > 24, returns null
                       x 3 -- 38
...
...

This is what is happening. You go deeper in the recursion. You go to a place where there is no going forward. So, you go back to the place before the current state. That is why when you are not able to proceed further with 21, recursion unwinds and lets you proceed the other path from 16. That is why start is 16 again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top