Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

85
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda