javascript 5 random non duplicating integers from

2019-02-22 10:12发布

问题:

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?

回答1:

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);
}


回答2:

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



回答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]