在递归Javascript中使用两个函数

时间:2017-02-12 00:24:51

标签: javascript arrays recursion

我试图理解这段代码是如何创建我正在寻找的数组组合但是我不清楚如何在递归中第二次传递相同的函数6。我一直在研究我对递归的理解,但我不确定第二次再次传递函数的确如此。对此的任何澄清都会有所帮助。

function string_recurse(active, rest) {
    if (rest.length == 0) {
        console.log(active);
    } else {
        string_recurse(active + rest.charAt(0), rest.substring(1, rest.length));
        string_recurse(active, rest.substring(1, rest.length));
    }
}
string_recurse("", "abc");

2 个答案:

答案 0 :(得分:0)

每次结束递归时(因此它到达if (rest.length == 0))它都会返回给调用者。调用者而不是回到自己的调用者(通常)再次调用递归。

看一下可以解释事情的一堆console.log的例子



function string_recurse(active, rest, i) {
    if (rest.length == 0) {
        console.log(active);
    } else {
        console.log('Calling 1st recursion at depth', i);
        string_recurse(active + rest.charAt(0), rest.substring(1, rest.length), i + 1);
        console.log('Ended first recursion, calling second one at depth', i);
        string_recurse(active, rest.substring(1, rest.length), i + 1);
        console.log('Ended second recursion at depth', i);
    }
}
string_recurse("", "abc", 0);




或者,如果它更好,这里的模式试图解释调用中的序列:

f("", "abc")
|
|
--- f("a", "bc")
    | 
    |
    --- f("ab", "c")
        |
        |
        --- f("abc", "") -> console.log()
        --- f("ab", "") -> console.log()
    |
    |
    --- f("a", "c") 
        |
        | 
        --- f("ac", "") -> console.log()
        --- f("a", "") -> console.log()
|
|
--- f("", "bc")
    |
    |
    --- f("b", "c")
        |
        |
        --- f("bc", "") -> console.log()
        --- f("b", "") -> console.log()
    |
    |
    --- f("c", "") -> console.log()

您可以从头到尾看到调用的顺序,您可以看到每个函数或有两个孩子或打印active的值

答案 1 :(得分:0)

运行此代码段,它可能会帮助您将其可视化:

 var h = 0;
 var i = 0;
 var j = 0;

 function string_recurse(active, rest, x) {
     h += x==='a' ? 1 : 0;
     i += x==='b' ? 1 : 0;
     j += x==='c' ? 1 : 0;
     console.log(`${x} (a${h} b${i} c${j}) active:${active}`);
     if (rest.length == 0) {
         //console.log(active);
     } else {
         string_recurse(active + rest.charAt(0), rest.substring(1, rest.length), "b");
         string_recurse(active, rest.substring(1, rest.length), "c");
     }
 }
 string_recurse("", "abc", "a");

控制台:

a(a1 b0 c0)有效:
   b(a1 b1 c0)有效:a    b(a1 b2 c0)有效:ab
   b(a1 b3 c0)有效:abc
   c(a1 b3 c1)有效:ab
   c(a1 b3 c2)有效:a    b(a1 b4 c2)有效:ac
   c(a1 b4 c3)有效:a    c(a1 b4 c4)有效:
   b(a1 b5 c4)有效:b
   b(a1 b6 c4)有效:bc
   c(a1 b6 c5)有效:b
   c(a1 b6 c6)有效:
   b(a1 b7 c6)有效:c
   c(a1 b7 c7)有效: