Can't wrap my head around this this recursion example [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-01-07 02:53:58

问题


So there is this recursion example in chap 3 of Eloquent JavaScript, it goes like this: Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite set of numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produces that number?

And the given code is..

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

Now there are couple of things which I don't understand. Like very first time we call the function what is it going to return? is it going to return (1, "1") and just ignore the inner function find?

and what is current and history in the example? I don't remember assigning their values?


回答1:


The first time you call findSolution() it will return the result of the last line of that function find(1, "1"). In that case "1" is history, which is being set by calling find. The value of current is 1, which was the first parameter in find(1, "1")

The important thing to understand is that you are calling a function that is calling a newly defined function find. The results of that function, which will recursively call itself is an exercise left to the reader (you). Whatever that result is will be returned by findSolution.



来源:https://stackoverflow.com/questions/65536432/cant-wrap-my-head-around-this-this-recursion-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!