-1

私の主な問題は、コードを理解することはもちろん、紙で問題を解決する方法を理解できないように見えること、または自分で書くことです。これが私が読んでいる本、EloquentJavaScriptからの抜粋です。

このパズルを考えてみましょう。1から始めて、5を足すか、3を掛けるのを繰り返すことで、無限の数の新しい数を生み出すことができます。数値が与えられると、その数値を生成する加算と乗算のシーケンスを見つけようとする関数をどのように記述しますか?

¶たとえば、最初に1に3を掛け、次に5を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));
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 に答える