So I'm writing a method to find recursively all of the permutations of a list of numbers.
I'm adding the result of each run, which is an number array, to a larger combos array. However, combos is becoming filled with empty arrays like this: [[],[],[]] instead of [[1,2,3],[3,2,1],[2,3,1] ...] but I know the combinations are being generated
Here is what I have:
var combos = [];
permuteHelper([1,2,3],[]);
console.log(combos); //printing blank array or arrays [[],[]]
function permuteHelper(list, combination){
if(list.length == 0){
combos.push(combination); //ERROR: combos only holds blank arrays (e.g. [[],[]] )
console.log(combination); //although this is printing correct list after each recursive run (e.g. [3,2,1] )
}
for(var i = 0; i < list.length; i++ ){
//pick a digit
var digit = list[i];
list.splice(i,1); //remove the character from the array
combination.push(digit);
//recursively keep picking
permuteHelper(list, combination);
//backtrack and put the digit back for next time
list.splice(i,0,digit);
combination.pop();
}
}
I've tried making combos non-global and updated the function header
function permuteHelper(list, combination,combos)
but combos is still not populated correctly. I'm new to js, not sure what I'm missing.