This question already has an answer here:
This has been asked dozens of times, but somehow, after reading many answers, I'm not convinced. I'm not cleared about the best way to do it, performance and code simplicity.
Should I set the list [1.. 100] and keep picking random (it will run 10 times) from there to another array, avoiding searching for it every new random?
Should I develop and run 10 times (at least) a random function to return a 1.. 100, checking if it is not a dupe and put it into an array?
Some Javascript function that I'm missing?
Thanks
This function adds all numbers from
betweenStart
tobetweenEnd
, randomizes them overrandomRuns
loops and returns a list withamount
entries:You can use a while loop to generate random numbers with
Math.random()
and add the numbers to aSet
which contains only unique values.You can also just use an Array and check if the generated random number already exists in it before pushing it to the Array.
For a more generic function, you can use this:
#2 would be the most efficient.
You could also use
Set
in a newer browser, which would be a little faster than manually checking for existence:This technique creates N1 numbers (the total range) and shuffles them, then picks the top N2 number (how many we actually want), we'll use Fisher-Yates shuffle.