Home > Software design >  Why is my matrix showing the wrong output?
Why is my matrix showing the wrong output?

Time:02-16

I am trying to find the permutations of the array [1,2,3] using recursion. Everything is working fine if I directly print out the permutations in the base case but I want to store all the permutations in a separate array. I am doing that by pushing the arrays into the matrix but it shows the wrong output that is all the arrays being pushed are the same. I can't find out what the bug is. Please help.

let arr = [1, 2, 3];
let matrix = [];
let index = 0;

function perm(arr, index) {
    if (index === arr.length) {
        console.log('arr:', arr);
        matrix.push(arr);
        return;
    }

    for (let i = index; i < arr.length; i  ) {
        [arr[i], arr[index]] = [arr[index], arr[i]];
        perm(arr, index   1);
        [arr[i], arr[index]] = [arr[index], arr[i]];
    }
}

perm(arr, index);
console.log(matrix);

This is the output that I am getting:

arr: [ 1, 2, 3 ]
arr: [ 1, 3, 2 ]
arr: [ 2, 1, 3 ]
arr: [ 2, 3, 1 ]
arr: [ 3, 2, 1 ]
arr: [ 3, 1, 2 ]
[
  [ 1, 2, 3 ],
  [ 1, 2, 3 ],
  [ 1, 2, 3 ],
  [ 1, 2, 3 ],
  [ 1, 2, 3 ],
  [ 1, 2, 3 ]
]

CodePudding user response:

you are pushing the same array arr multiple time into matrix, so when you update it later, it update all the ligne in matrix since they are the same reference to the same array.

Try duplicating the array arr before:

matrix.push(arr.slice());
  • Related