I am trying to make an array of all the permutations for a given string using Heap's Algorithm. The function prints the correct array results when I use console.log to test. However, when I try to push all of the arrays into a new array it pushes the same initial array every time.
In this example it pushes [a, a, b] 6 times.
First of all, why is it doing this? Second, how do I get around it and push all of the correct results into my new array.
function permAlone(str) {
//make str into array
var arr = str.split('');
var allArrays = [];
//Heap's Algorithm to make new array with all permutations
var swap = function (array, pos1, pos2) {
var temp = array[pos1];
array[pos1] = array[pos2];
array[pos2] = temp;
};
var permute = function(array, n) {
n = n || array.length;
if (n === 1 ) {
console.log(array);
//allArrays.push(array);
}
else {
for (var i=1; i <= n; i += 1) {
permute(array, n-1);
if (n%2) {
var j=1;
}
else {
j=i;
}
swap(array, j-1, n-1);
}
}
};
permute(arr);
//console.log(allArrays);
}
permAlone('aab');