Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

484
Views
¿Por qué el número aleatorio no cambia en cada iteración?

Quiero establecer una matriz con números aleatorios. Primero usé una función para crear una matriz 0, luego recorrí cada celda y le asigné un número aleatorio.

 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)

Cuando ejecuto el código, obtengo el siguiente resultado. ingrese la descripción de la imagen aquí

Como se puede ver en la imagen, el valor aleatorio cambia solo cuando i cambia. ¿Esto está relacionado con que JS sea asíncrono o porque los números aleatorios generados por Math.random tienen una relación con la marca de tiempo?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Array.prototype.valueOf es Object.prototype.valueOf y simplemente devuelve el valor del receptor ( this argumento). No crea una copia de la matriz, por lo que está map ping a una matriz externa que contiene la misma matriz interna en cada índice. En su lugar, utilice

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

o el formato más simple y convencional

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

También es posible que desee hacer de d una función de devolución de llamada y llamarla, de modo que cree su matriz directamente mediante matrix(4, 3, () => getRandomArbitrary(-1, 1)) en lugar de inicializarla con 0 y luego hacer un bucle. para cambiar los valores.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!