Javascript 5 random non-duplicate integers from 0 to 20

What is the best way to create 5 random non-duplicate integers from 0 to 20?

I think use Math.random with the floor, loop it 5 times, check for duplicates, if they are repeated, random again.

How?

+5
source share
3 answers

Change . The best solution that this or others posted here can be found in this answer to this question when asked to answer in 2008. To summarize: generate an array (as Darin suggests in his answer below) and shuffle it using Knuth-Yates- Fisher shuffle . Do not use a naive shuffle, use one that is known to have good results.


This is pretty much how I would do it, yes. I would probably use an object to track the integers that I already had, as it is convenient. For instance:.

var ints = {};

Then, as soon as you have created a new random number, check it and possibly save it:

if (!ints[number]) {
    // It a keeper
    ints[number] = true;
    results.push(number);
}
0
source

0 20, 5 .

+7

Late answer that 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]

+3
source

All Articles