What's the best way to generate 5 random non duplicating integers from 0 - 20?
I'm thinking, use Math.random with floor, loop it 5 times, check for duplicates, if duplicate, random again.
What's your way?
You could generate an array of numbers from 0 to 20, shuffle it and take the first 5 elements of the resulting array.
late answer i know, but:
var a=[];
while(a.length <3) {
var n = Math.round(Math.random() * 20);
if (a.indexOf(n)==-1) a.push(n);
}
=> [14, 17, 19]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With