Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

488
Visualizações
Why random number doesn't change in every iteration?

I want to set a matrix with random numbers. I used a function to create a 0 matrix first, then loop through every cell and assign a random number to it.

function getRandomArbitrary(min, max) {
  let value = Math.random() * (max - min) + min;
  if (value === 0)
    return getRandomArbitrary(min, max);
  return value;
}

function matrix(m, n, d) {
  return Array.apply(null, new Array(m)).map(
    Array.prototype.valueOf,
    Array.apply(null, new Array(n)).map(
      function() {
        return d;
      }
    )
  );
}

let weight_1 = matrix(4, 3, 0);

for (let i = 0; i < 4; i++) {
  for (let j = 0; j < 3; j++) {
    weight_1[i][j] = getRandomArbitrary(-1, 1);
  }
}

console.table(weight_1)

When I run the code, I get the following output.enter image description here

As can be seen in the picture, the random value changes only when i changes. Is this related to JS being asynchronous or because random numbers generated by Math.random has a relation to timestamp?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Array.prototype.valueOf is Object.prototype.valueOf, and simply returns the receiver value (this argument). It does not create a copy of the array - so you are mapping to an outer array that contains the same inner array at every index. Instead, use

function matrix(m, n, d) {
  return Array.apply(null, new Array(m)).map(
    function() {
      return Array.apply(null, new Array(n)).map(
        function() {
          return d;
        }
      );
    }
  );
}

or the simpler and more conventionally formatted

function matrix(m, n, d) {
  return Array.from({length: m}, () =>
    Array.from({length: n}, () =>
      d
    )
  );
}

Also you might want to make d a callback function and call it, so that you create your matrix directly by matrix(4, 3, () => getRandomArbitrary(-1, 1)) instead of initialising it with 0 and then looping it to change the values.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda