0

Here is my js:-

function recPerm(rest, soFar) { 
    var next;
    var remaining;
    var output=[];
    if (rest === '') {
        console.log(soFar); //outputting strings..and this works
        output.push(soFar); 
    } else {

        for (var i = 0; i < rest.length; i++) {
            remaining = rest.substr(0,i) + rest.substr(i+1,rest.length-1);
            next = soFar + rest[i];
            recPerm(remaining, next);
        }

    }
    return output; //returns an empty array in the end
}

var out=recPerm('abc',''); 
console.log(out);  //prints empty array

Recursively, I am trying to print permutations of an input string. I am passing the input string and a blank string which recursively then calls this function with remaining string and next individual char in string to be considered. Inside base case, I am succesfully able to log individual strings . But somehow its not saving it in my array towards the end. Is there something i am missing out in my JS?

3
  • inside your function you should do something like output.push(somevalue); Commented Aug 7, 2016 at 18:51
  • Each call to recPerm is creating and returning a new Array, which you're then ignoring in the recursive calls. You'd need to add the content of that returned array to the array in the scope of the caller. Commented Aug 7, 2016 at 18:51
  • String.prototype.substr() taks length of the sub-string as the second parameter. I guess you might be dong wrong with passing indices to it. Commented Aug 7, 2016 at 19:26

1 Answer 1

1

Your problem resides on the output variable, that is private to the recPerm function and when you recursively call recPerm, of course, it will be recreated... I suggest You to pass that variable as parameter:

function recPerm(rest, soFar, output) { 
  var next;
  var remaining;
  output = Array.isArray(output) ? output : [];
  
  if(rest === '') {
    output.push(soFar); 
  } else {

    for (var i = 0; i < rest.length; i++) {
      remaining = rest.substr(0,i) + rest.substr(i+1,rest.length-1);
      next = soFar + rest[i];
      recPerm(remaining, next, output);
    }
    
  }
  
  return output; //returns an empty array in the end
}

var out=recPerm('abc',''); 
console.log(out); 

Sign up to request clarification or add additional context in comments.

2 Comments

Great solution. Thanks
Post an explanation of your answer. These code-only answers are low-quality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.