¿Cómo hacer Math.random () en bucle for con diferentes valores?

Dec 04 2020

Intento llenar la matriz scon 9999 conjuntos de valores diferentes m[i][random], aquí está el código:

let m = [[22,0],[53,0],[64,0],[45,0],[34,0]];
let l = m.length;
let s = [];
for (let j = 0; j < 9999; j++)
{
  for(let i = 0; i < m.length; i++)
  {
    let x = Math.floor(Math.random()*l);
    m[i][1] = x; 
  }
  s.push(m);
} 

Pero obtengo los mismos valores:

console.log(s)
[ [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ], ...]

¿Qué estoy haciendo mal? ¿Como arreglarlo?

Respuestas

6 CertainPerformance Dec 04 2020 at 01:51

Cree el msubarreglo dentro del ciclo (de modo que tenga un subarreglo separado para cada iteración), no fuera de él; afuera, solo ha creado una única matriz en la memoria a la que apunta cada índice.

let s = [];
for (let j = 0; j < 9999; j++)
{
  let m = [[22,0],[53,0],[64,0],[45,0],[34,0]];
  let l = m.length;
  for(let i = 0; i < m.length; i++)
  {
    let x = Math.floor(Math.random()*l);
    m[i][1] = x; 
  }
  s.push(m);
}

O, más funcionalmente y todo a la vez con Array.from:

const s = Array.from(
  { length: 2 },
  () => [[22,0],[53,0],[64,0],[45,0],[34,0]]
          .map(([num]) => [num, Math.floor(Math.random() * 5)])
);
console.log(s);