I'm trying to implement a recursive permutation generator in Javascript, but I can't seem to get it to go through all the recursion branches (see the Results below).
I know I'm missing something important, can someone help me understand where I've gone wrong?
var permute = function(input){
var permutation = function (arr, position){
if(position >= arr.length-1){
results.push(arr);
}else{
var tempSwap="";
for(i=position;i<arr.length;i++){
tempSwap = arr[position];
arr.splice(position,1,arr[i]);
arr.splice(i,1,tempSwap);
permutation(arr,(position+1));
}
return;
}
};
permutation(input,0);
};
var results=[];
permute(['a','b','c']);
console.log(results);
Results: [ [ 'a', 'c', 'b' ], [ 'a', 'c', 'b' ] ]
inputarray. You will need to create some copies!splicecalls. They're equivalent toarr[position] = arr[i]; arr[i] = tempSwap;