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

486
Views
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 answers
Answer question

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