5

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?

Harry
  • 52,711
  • 71
  • 177
  • 261

3 Answers3

7

You could generate an array of numbers from 0 to 20, shuffle it and take the first 5 elements of the resulting array.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

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]

herostwist
  • 3,778
  • 1
  • 26
  • 34
0

Edit: A better solution that this or the others posted here can be found in this answer to this question when it was asked back in 2008. Summarizing: Generate an array (as Darin suggests in his answer below) and shuffle it using the Knuth-Yates-Fisher shuffle. Don't use a naive shuffle, use one that's known to have good results.


That's pretty much how I'd do it, yes. I'd probably use an object to keep track of the integers I already had, since that's convenient. E.g.:

var ints = {};

Then once you've created a new random number, check it and possibly keep it:

if (!ints[number]) {
    // It's a keeper
    ints[number] = true;
    results.push(number);
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I'm not sure why the previous person downvoted, but I am downvoting because this is a theoretically never-ending algorithm. In other words, it is _possible_ that a random generator can generate the same values over and over again, causing your loop to never end. With only five values, this is practically impossible, but what happens when you need 5000 items? Again, in practice, it won't be never-ending but the time it takes is non-deterministic. There are other algorithms (like Darin's) which will yield deterministic results. I would go with one of them instead. – Brian Genisio Aug 20 '13 at 16:43
  • @BrianGenisio: Perhaps. But using the shuffle Darin pointed to will not yield good random results. See [this answer](http://stackoverflow.com/questions/196017/unique-random-numbers-in-o1) for why you need something more sophisticated. – T.J. Crowder Aug 20 '13 at 17:05