1

When I try to generate a new random number using Math.random() it gives me the EXACT same answer every single time no matter what, but only in certain uses.

By the way I have a custom random function:

function random(min, max) {
 return Math.random() * (max - min + 1) + min;
}

For example, this code does exactly what I want it to, it fills each slot in dataset.data[I][ii] to a NEW random number.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index] = point.map(() =>
    Math.round(random(0, screen.get().width))
 );
});

However, when I use this code, It fills the array with the exact same random number each time.

dataset.data.forEach((point, index) => {
 //fill dataset with random numbers
 dataset.data[index][0] = Math.round(random(0, screen.get().width));
 dataset.data[index][1] = Math.round(random(0, screen.get().height));
});

I keep encountering this issue and I do not understand it, I do understand that there are at times large quantities of the same number, but no matter what I do, in certain circumstances like these, only one way of writing it works, which is not helpful.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • 1
    Let's start with that there is no built in function in javascript called `random`. – gforce301 Dec 31 '19 at 05:42
  • 1
    [mcve] is needed here. Also, keep in mind that the definition of "random number" doesn't prohibit dupes. – ggorlen Dec 31 '19 at 05:43
  • You forgot to add `Math.floor()` here: `Math.floor(Math.random() * (max - min + 1)) + min`. Otherwise, `Math.round(random(...))` will always return `min` or `min + 1` – adiga Dec 31 '19 at 05:55
  • You can close it as a duplicate of [Generating random whole numbers in JavaScript in a specific range?](https://stackoverflow.com/questions/1527803) – adiga Dec 31 '19 at 05:57
  • @damien not able to reproduce the case mentioned,For me a new random number is being generated – Thakur Karthik Dec 31 '19 at 06:12
  • I see, what code editor are you using? im using codesandbox.io because its the best editor I could find, could that be the problem? – Damien Hall Dec 31 '19 at 06:13

1 Answers1

0

Math.random(), when mapped to an array, generates a new random number for each index in that array, so a workaround to the problem of mine is using the index in an if statement.

arr = new Array(2).fill([]);
arr.forEach((point, index) => {
    arr[index] = point.map((array, index) => i===theSpotInYourArray?returnthis:orreturnthis
})