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

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

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 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