Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript 5 random non duplicating integers from 0 - 20

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?

like image 344
Harry Avatar asked Apr 21 '11 07:04

Harry


2 Answers

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

like image 65
Darin Dimitrov Avatar answered Sep 24 '22 23:09

Darin Dimitrov


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]

like image 31
herostwist Avatar answered Sep 22 '22 23:09

herostwist