本文介绍了${history} 如何记录程序如何达到最终解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个来自 Eloquent JS 的例子解释了递归是如何工作的.
大体上我理解.但我不明白 ${history} 如何记录通往最终解决方案的路径.

This example from Eloquent JS explains how recursion works.
I understand in general. BUT I couldn't get how ${history} records the path toward the final solution.

我在 https://cutt.ly/1wFYrlQ

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"); 
}
console.log(findSolution(24)); // → (((1 * 3) + 5) * 3)

只需要了解历史绑定的工作原理?

Just need to understand how the history binding works?

推荐答案

在上面的例子中你看到函数 find(current, history) 被调用返回查找(1,1");在函数 findSolution(target) 内

In the example above you see function find(current, history) being called from return find(1, "1"); within function findSolution(target)

我简化了那个例子,它做同样的事情

I have simplified that example it does the same thing

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

console.log(find(1, "1", 88)); 

我会尽力解释

(${history} + 5) 等同于:'(' + history + 5 + ')'
由于 history 在第一次调用中等于 "1",所以 history = "(1 + 5)" 作为字符串.

(${history} + 5) is same as: '(' + history + 5 + ')'
since history is equal to "1" in the first call, history = "(1 + 5)" as a string.

电流等于1当前 + 5 = 6,历史 = "(1 + 5)",目标 88现在函数调用它自传递 find(6, "(1 + 5)", 88)

current is equal to 1 current + 5 = 6, history = "(1 + 5)", target 88 now the function calls it self passing find(6, "(1 + 5)", 88)

next find 调用它自己再次传递

next find calls it self again passing

find( 11, '(' + (1 + 5) + 5 + ')', 88 ) 

并且相同的过程继续直到如果 (current == target) 为 true

and the same process continue until if (current == target) gets true

这篇关于${history} 如何记录程序如何达到最终解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:44