需要解释的Javascript代码(递归示例)



我的主要问题是我似乎无法理解如何在纸上解决问题,更不用说理解代码了,或者自己写。这是我正在读的一本书《雄辩的JavaScript》的节选。

考虑这个谜题:从数字1开始,反复地加上5或乘以3,可以产生无限数量的新数字。你会怎么写一个函数,给定一个数字,试着找出一系列的加法和乘法来得到这个数字?

例如,数字13可以先用1乘以3,然后再加5两次。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));
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");
 }

最新更新