javascript - Why is my variable referencing the global scope variable? -


i tried write function finds possible permutations given array of numbers. here code.

var perm = []; var usedchar = [];  function findallpermutations(arr) {    (var = 0; < arr.length; i++) {     var x = arr.splice(i,1)[0];     usedchar.push(x);      if (usedchar.length == 3) {       perm.push(usedchar);     }      findallpermutations(arr);     usedchar.pop();     arr.splice(i,0,x);   } }  findallpermutations([1,2,3]);  console.log(perm); //-> [[],[],[],[],[],[]] 

i expect get:

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 

can explain why i'm not getting answer?

you're using same array holds intermediate result storage algorithm , things getting mixed up. need either separate 2 or make sure clone usedchar array before pushing perm array. plunker: http://plnkr.co/edit/hq6q8fo8s0k21cisqkvt

  var perm = [];   var usedchar = [];   var = [];    function findallpermutations(arr) {     (var = 0; < arr.length; i++) {     var x = arr.splice(i,1)[0];     usedchar.push(x);      if (usedchar.length == 3) {       perm.push(usedchar.slice());     };      findallpermutations(arr);     usedchar.pop();     arr.splice(i,0,x);   }; };  findallpermutations([1,2,3]); console.log(perm); 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -