-2

Translated (apparently wrongly) from a C++ book. If I can get it to work, then I can start trying to understand it.

function recPermute(soFar, rest)
{
    if (rest==="")
    {
        console.log(soFar);    
    }
    else
    {
        for(i=0; i<rest.length; i++) // <<< error was in not declaring the "i"
        {
            var next = soFar + rest[i];
            var remaining = rest.substr(0,i) + rest.substr(i+1);
            recPermute(next, remaining);
        }
    }
}   


function listPerm(s)
{
    recPermute("",s);
}

listPerm("kitcap")
dwilbank
  • 2,470
  • 2
  • 26
  • 37

3 Answers3

1

for JavaScript, use charAt(), instead of using array like acessing.

var next = soFar + rest.charAt(i);
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
1

You need to declare i so it's scoped to recPermute:

for(var i=0; i<rest.length; i++)

Without the var, it'll be created as a global so each call to recPermute will alter it for any other calls.

Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
0

One thing that could be an issue is you are using effectively the same i for each call to the function. You need to declare a local i or it will be declared in the global scope.

for(var i = 0; ....
doogle
  • 3,376
  • 18
  • 23