无法理解这个递归示例 [英] Can't wrap my head around this this recursion example

查看:66
本文介绍了无法理解这个递归示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在 Eloquent JavaScript 的第 3 章中有这个递归示例,它是这样的:考虑这个谜题:从数字 1 开始,重复加 5 或乘以 3,一个无限的集合号码可以生产.你会如何编写一个函数,给定一个数字,试图找到一系列这样的加法和产生那个数字的乘法?

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?

给定的代码是..

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

现在有几件事我不明白.就像我们第一次调用函数一样,它会返回什么?它会返回 (1, "1") 并忽略内部函数 find 吗?

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?

推荐答案

第一次调用 findSolution() 会返回该函数最后一行的结果 find(1, 1").在那种情况下,1"是历史,它是通过调用find 来设置的.current 的值为 1,这是 find(1, "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")

要理解的重要一点是,您正在调用一个正在调用新定义函数 find 的函数.该函数的结果将递归调用自身,这是留给读者(您)的练习.无论结果如何,findSolution 都会返回.

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.

这篇关于无法理解这个递归示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆