探索需要的Javascript代码(递归示例)

时间:2013-03-22 14:00:31

标签: javascript

我的主要问题是我似乎无法理解如何在纸上解决问题,更不用说了解代码,或者自己编写代码。下面是我正在阅读的一本书Eloquent JavaScript的摘录。

考虑这个难题:从数字1开始并重复加5或乘以3,可以产生无限量的新数字。你会如何编写一个函数,给定一个数字,试图找到一个产生该数字的加法和乘法序列?

¶例如,可以通过先将1乘以3然后再加2来两次来达到数字13。根本无法达到15号。

¶以下是解决方案:

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

 print(findSequence(24));

1 个答案:

答案 0 :(得分:1)

function findSequence(goal) {

   // define a function that has a 'start' number (current total),
   // and a string that is the history of what we've done so far
   // (and note that for this function, the 'goal' parameter above is in scope).
   function find(start, history) {
     // if we've reached the goal, return the string that says how we got there
     if (start == goal)
      return history;
     // if we've overshot, return null
     else if (start > goal)
       return null;
     else
       // call this same function (recursion) with two different possibile ways of
       // getting closer to the goal - one adding 5 and one multiplying by 3...
       // the or ('||') operator will return the first of the two that is not null
       return find(start + 5, "(" + history + " + 5)") ||
              find(start * 3, "(" + history + " * 3)");
   }
   // start at 1
   return find(1, "1");
 }