I'm stuck with some heap's permutation algorithm. I wrote some JavaScript code to recursively find every possible permutation of a value: either an array or a string. My code seems to work perfectly when I console.log()
the permuted values but when I push them to another array I get the same value for all of them. I'm confused.
My code contains two separate functions: one does the swapping of the elements and the other one recursively finds the possible permutation:
arr = ["a", "b", "c"];
newArr = [];
// swap mechanism here
function swap(arr, pos1, pos2) {
var temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
};
function perm(arr, nArr, n) {
n = n || arr.length;
if (n === 1) {
console.log(arr); // console.log() works great
newArr.push(arr); // pushing the permuted values does not
}
else {
for(var i = 1; i <= n; i += 1) {
perm(arr, nArr, n - 1);
if (n % 2) {
var j = 1;
}
else {
var j = i;
}
swap(arr, j - 1, n - 1);
}
}
};