Javascript recursion not functioning as expected -
i ported method java javascript. "original" array 9 objects in it, java code made 3000 subarrays of size 4.
in javascript code 6 subarrays of size 9.
var hitterarray = new array(); function permute(level, permuted, used, original){ if (level == 4) { hitterarray.push(permuted); //array of arrays } else { (i = 0; < original.length; i++) { if (!used[i]) { used[i] = true; permuted.push(original[i]); permute(level + 1, permuted, used, original); used[i] = false; } } } }
i want 3000 subarrays of size 4, why not working?
this how initialize permute function:
var used = new array(results.length); for(p = 0; p < used.length; p++){ used[p] = false; } var permutearray = new array(); permute(0, permutearray, used, results);
insight appreciated
i think error on loop, need declare i
var
otherwise make global variable.
for(var = 0; ....
another thing might have impact passing references arrays: used
, permuted
have impact on result, consider cloning arrays array.slice()
create new copies of them.
and think permutations of 4 objects out of 9 should 3024 (9*8*7*6), should 3024 arrays of 4
edit
function permute(level, permuted, used, original){ if (level == 4) { hitterarray.push(permuted); //you don't need create copy here, if performance not issue, might want it, clarity } else { (var = 0; < original.length; i++) { if (!used[i]) { var newused = used.slice(); var newpermuted = permuted.slice(); newused[i] = true; newpermuted.push(original[i]); permute(level + 1, newpermuted, newused, original); //used[i] = false; //this won't needed you've created copy of original 1 } } } }
Comments
Post a Comment