JavaScriptの再帰基本



再帰とは何か

The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion). https://developer.mozilla.org/en-US/docs/Glossary/Recursion

  • 自分自身を呼び出し、ベースと再帰的なケースを持つ関数.関数は結果に到達するまで本質的に再起動します.

  • 2例

  • ベースケース-私たちの答えを返す必要がありますか?いつ停止する必要がありますか?

  • 再帰的なケース-我々はどのように我々の議論を操作しますか、あるいは、我々はもう一つの再起動のために引数を調節することができますか?

  • 例- count ()
    "1羊"を出力する関数count ()を作成する入力番号「X羊」までずっと
    テクニックを使って解決しましょう

  • p - integer ( x )羊の数、count = 0のデフォルト引数で、現在の羊番号
  • を追跡します

  • R - 1からx
  • に羊をログアウトしてください

  • 下記参照
  • // countSheep(3)
    // 1 sheep...
    // 2 sheep...
    // 3 sheep...
    
    

  • p -
  • base case -すべての羊がカウントされたときに戻る( count == x )
    再帰的な場合- 1を加えることによってカウントを変更して、現在のカウントのコンソールを返します
    function countSheep(x, count=0) {
      // BASE CASE
      // return if count equals x, which means every sheep is counted
    
      // RECURSIVE CASE
      // modify argument by adding 1 to count
      // log current count & reinvoke w/ modification
    }
    
    
    さて、コードロジックを実装します.
    function countSheep(x, count=0) {
      // BASE CASE
      // return if count equals x, which means every sheep is counted
      if (count === x ) return;
    
      // RECURSIVE CASE
      // modify argument by adding 1 to count
      count++
      // log current count & reinvoke w/ modification
      return console.log(x + ' sheep...') + countSheep(x, count)
    }
    

    結論
    再帰的な解決策を見つけるとき、常に基本的なケースと再帰的なケースが何であるかについて、心に留めておいてください.それは良い方法を開始することです!
    覚えて.ハッピーコーディング、友達!=