Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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 ]
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

Try duplicating the array arr before:

matrix.push(arr.slice());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!