I tried to write a function that finds all possible permutations given an array of numbers. Here is my code.
var perm = [];
var usedchar = [];
function findAllPermutations(arr) {
for (var i = 0; i < 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 to get:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Can someone explain why I'm not getting this answer?
console.logis a dead giveaway; but OP, you do need to tag questions appropriately (and indent them correctly, or no-one will bother to look for where your scope is).