Rajat Bansal
Rajat Bansal

Reputation: 183

Recursive solution : string permutation. Unable to return array of permutation strings in javascript

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?

Upvotes: 0

Views: 65

Answers (1)

Hitmands
Hitmands

Reputation: 14179

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); 

Upvotes: 1

Related Questions