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?
output.push(somevalue);recPermis 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.