Javascript Recursive function. Wrong results while storing data in array

Viewed 1074

While trying to get all permutations using Heap's algorithm, I met trouble storing the results in array.

The result generated is (from console.log(arr);)
["1", "2", "3"]
["2", "1", "3"]
["3", "1", "2"]
["1", "3", "2"]
["2", "3", "1"]
["3", "2", "1"]

but only the last value is stored in the arr, and the array stored somehow is this (from console.log(JSON.stringify(allPermutations)); )
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]
["3", "2", "1"]

var allPermutations = [];

function swap(arr,index1,index2){
    var dummy = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = dummy;
    return arr;
}

function generate(n,arr){
    if(n==1){
        console.log(arr);
            //result:
            //["1", "2", "3"]
            //["2", "1", "3"]
            //["3", "1", "2"]
            //["1", "3", "2"]
            //["2", "3", "1"]
            //["3", "2", "1"]
        allPermutations.push(arr);
    }else{
        for(var i=0;i<n-1;i++){
            generate(n-1,arr);
            if( n%2 ==0){
                arr = swap(arr,i,n-1);
            }else{
                arr = swap(arr,0,n-1);
            }
        }
        generate(n - 1, arr);
    }
}

generate(3,['1','2','3']);

console.log(JSON.stringify(allPermutations));
/*result:
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]
["3","2","1"]*/

What's wrong with this? Would love to understand. Thanks

2 Answers
Related