-1

我的主要问题是我似乎无法理解如何在纸上解决问题,更不用说理解代码或编写自己的代码了。这是我正在阅读的一本书 Eloquent 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));
4

1 回答 1

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");
 }
于 2013-03-22T14:07:41.603 回答