Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my matrix showing the wrong output?

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 ]
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading