I have a question regarding javascript Math.random()
:
I have (for a game I'm building) to randomly generate every number from a given set (i.e. from 0 to 1000) and every time I have to generate a number, I have to check if that number has already been "generated".
The solution is pretty easy thinking about a simple algorithm that checks if the random integer is already present in the generated set. It loops generating numbers until it can't find it. A snippet below:
/* ... */
for(var i = 0; i<upperBound; i++){
var randN = Math.floor(Math.random()*upperBound);
while(myRandomNumbers.contains(randN)){
loops++;
randN = Math.floor(Math.random()*upperBound);
}
myRandomNumbers.push(randN);
}
/* ... */
I'd like to know: is this the best way to achieve this? or are there any ways, instead of looping until it generates a "good" number, to exclude a particular set in the random generation?
Thanks a lot everyone!