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.
When you get combination
as a parameter to your function, it's treated as a reference. Any change to combination
will change the original variable. You hand over that reference to each new call of permuteHelper
and therefore always modify the original array.
A primitive solution with few code changes would be:
var combos = [];
permuteHelper([1, 2, 3], [], []);
function permuteHelper(list, _combination) {
var combination = Object.assign([], _combination);
if (list.length == 0) {
combos.push(combination); //this only has a blank array of
arrays(e.g. [[], []])
console.log(combination); //prints correct permuted list after each recursive trial (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, combos);
//backtrack and put the digit back for next time
list.splice(i, 0, digit);
combination.pop();
}
}
Like that, you create a new object combination
from the parameter _combination
that can be modified as you please.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.