你能解释一下第 3 章 Eloquent js 中的这个递归解决方案吗?

Can you explain this recursive solution from Chap 3 Eloquent js?

本文关键字:js 递归 解决方案 Eloquent 能解释 一下      更新时间:2023-09-26

我正在用雄辩的javascript完成第3章,递归刚刚被引入,我试图围绕这个概念。

也有人可以解释函数中的第二个参数历史吗?

历史已经定义了吗?

考虑这个难题:从数字 1 开始,反复加 5 或乘以 3,可以产生无限数量的新数字。你会如何编写一个函数,在给定一个数字的情况下,试图找到产生该数字的此类加法和乘法序列?例如,数字 13 可以通过先乘以 3 然后加 5 两次来达到,而数字 15 根本无法达到。

function findSolution(target) {
  function find(start, history) {
    if (start == target)
      return history;
    else if (start > target)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}
console.log(findSolution(24));

console.log 将打印 findSolution(24) 返回的值,其中 24 是目标。

现在,当函数 findSolution() 被执行时,它会调用(调用)具有 2 个参数的函数 "find":start = 1,history = "1",然后返回要打印的内容。

意思是find()在findSolution()中调用,因此return将发回在findSolution中调用的值。

在我们的例子中:

如果开始 === 目标

return history //(to findSolution. let's call it "H")
return H to console.log() // prints 1

否则,如果>目标

开始
return null //(to findSolution, let's call it N)
return N to console.log() // prints null

否则,如果开始小于目标, 返回 A ||乙

A = find(start + 5, "(" + history + " + 5)")
B = find (start * 3, "(" + history + " * 3)")

意思是,如果 A 是真,则返回 A,否则返回 B;在函数返回之前计算 A 或 B。

让我们一步一步地完成它:

find 将一次又一次地调用,启动参数递增 5即:

return find(1, "1")    //  start = 1,   history = "(1 + 5)"    
return find(6, history)   //   start = 6,   history = "(1 + 5 ) + 5"   
return find(11, history)    //  start = 11,   history = "(1 + 5) + 5 ) + 5"   
return find(16, history)    //  start = 16,   history = "(1 + 5) + 5 ) + 5 ) + 5"   
return find(21, history) start = 21,   history = "(1 + 5) + 5 ) + 5 ) + 5 ) + 5"   

现在下一个值将是 26。 由于 26> 22,"find" 将返回 B

return find(63, history) start = 21 * 3 =  63,      
//since 63 > 24,  "null" is returned where start = 16,    

start 是 16 而不是 63,因为它是一个参数。它没有更改,并且对调用期间发生的 5 增量一无所知。

find(21*3, history) , 48> 24 所以返回 null,其中 start = 11
find(11 *3, 历史记录) , 33> 24 所以返回 null,其中开始 = 6
find(6*3,历史记录),开始 = 18 和 18 <24 所以 A 将是真实的开始将增加 5
返回查找( 18 + 5, 历史)
返回查找(23 + 5,历史记录)28> 24,A 为空,B 为求值

。依此类推,直到开始等于 24

调用函数 find 时指定历史记录。如果不同时提供历史记录值,则无法调用函数find。请记住,该函数在被调用之前不会运行,因此历史记录不会获得值,直到它被告知其值"1"return find(1, "1");变量历史记录的定义是每当调用find时都是逗号后面的事物。

啊,我记得我把头撞了很久......

作者在函数findSolution中定义函数find,这很混乱

如果我这样重写它,你会得到它:

function find(start, history) {
    if (start == target)
      return history;
    else if (start > target)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
}
function findSolution(target) {
  return find(1, "1");
}
console.log(findSolution(24));