Como fazer Math.random () em for-loop com valores diferentes?

Dec 04 2020

Tento preencher a matriz scom 9999 conjuntos diferentes de valores m[i][random], aqui está o 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);
} 

Mas recebo os mesmos 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 ] ], ...]

O que estou fazendo errado? Como corrigi-lo?

Respostas

6 CertainPerformance Dec 04 2020 at 01:51

Crie o msubarray dentro do loop (para que você tenha um subarray separado para cada iteração), não fora dele - fora, você criou apenas um único array na memória para o qual cada índice aponta.

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);
}

Ou, mais funcionalmente e de uma vez com 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);