Sunday, March 1, 2009

Generating a list of unique random numbers

Here's a useful function for generating a list of N random numbers from a larger list M:
function randList(max:Number, num:Number, shuffled:Boolean):Array {
 var tempArray:Array = [];
 for (i = 0; i < max && num > 0; ++i) {
  if (Math.floor(Math.random() * (max - i)) < num) {
   tempArray.push(i + 1);
   num--;
  }
 }
 if (shuffled) {
  tempArray.sort(function () {
   return Math.floor(Math.random() * 2) ? true : false;
  });
 }
 return (tempArray);
}

Just provide the maximum number (M) in your list and the number of items (N) you wish to generate from that list:
// to generate an array of 10 unique sequential numbers
// between 1 and 10
var myArr:Array = randList(10, 10);
trace(myArr);
// to generate an array of 5 unique sequential numbers
// between 1 and 100 
var myArr:Array = randList(100, 5);
trace(myArr); 

Finally, the function also allows for the list of N random numbers to be shuffled:
// to generate an array of 10 unique shuffled numbers
// between 1 and 10
var myArr:Array = randList(10, 10, true);
trace(myArr);
// to generate an array of 5 unique shuffled numbers
// between 1 and 100
var myArr:Array = randList(100, 5, true);
trace(myArr); 

2 comments:

Lostinsider said...

Wow that what i was looking for thanks a lot man , can you do that for 2 specified number i mean is there any way to do random generated numbers between two number not just 0 to any !

glosrfc said...

Sure there is. I've altered the function to do just that in this follow-up post