Nayla
Nayla

Reputation: 21

why is this heap algorithm for permutation not working;

i'm preparing for an interview and was trying heap's algorithm for permutation with javascript. so the code works fine when i try to print to console.

function per(a, size){
    if(size === 1){
        console.log(a);
    }

    for(let i = 0; i < size; i++){
        per(a, size-1;
        if(size % 2 === 1){
            let temp = a[0];
            a[0] = a[size - 1];
            a[size - 1] = temp;
        }else{
            let temp = a[i];
            a[0] = a[size -1];
            a[size - 1] = temp;
        }
    }
}
let a = [1,2,3];
per(a, a.length,count);
console.log(count);

but when i try to put the result into an array it doesn't work.

function per(a, size){
    if(size === 1){
        count.push(a);
    }

    for(let i = 0; i < size; i++){
        per(a, size-1);
        if(size % 2 === 1){
            let temp = a[0];
            a[0] = a[size - 1];
            a[size - 1] = temp;
        }else{
            let temp = a[i];
            a[0] = a[size -1];
            a[size - 1] = temp;
        }
    }
}
let count = [];
let a = [1,2,3];
per(a, a.length,count);
console.log(count);

it prints this:

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

Upvotes: 0

Views: 118

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

count.push(a.slice()); // push a shallow-copy of the array

As an aside, you don't need a temporary variable to swap two items.

[a[0], a[size-1]] = [a[size-1], a[0]];

Upvotes: 1

Related Questions