Friday, July 17, 2009

Generate unique random numbers within a range

Following on from a previous post on how to generate a list of unique random numbers, this similar function will allow you to do the same...but within a predefined range of numbers:

function randListFromRange(firstNo:Number, lastNo:Number, num:Number, shuffled:Boolean):Array {
var tempArray:Array = [];
for (i = firstNo - 1; i < lastNo && num > 0; ++i) {
if (Math.floor(Math.random() * (lastNo - i)) < num) {
tempArray.push(i + 1);
num--;
}
}
if (shuffled) {
tempArray.sort(function () {
return Math.floor(Math.random() * 2) ? true : false;
});
}
return (tempArray);
}

To use this function, just provide the first and last numbers in your range, and the number of items you wish to generate from that list. For example, you might want to create an array of 7 unique random numbers that lie between 36 and 83:

// to generate an array of 7 unique sequential numbers
// between, and including, 36 and 83
var myArr:Array = randListFromRange(36, 83, 7);
trace(myArr);

As previously, the function still allows for the list of random numbers to be shuffled:

// to generate an array of 7 unique shuffled numbers
// between, and including, 36 and 83
var myArr:Array = randListFromRange(36, 83, 7, true);
trace(myArr);

Two points to note:
1. If your first number is greater than your last number, then no random numbers will be generated. For example:

var myArr:Array = randListFromRange(20, 10, 5);
trace(myArr); // outputs nothing

2. If the specified range is smaller than the desired number, the function will return every integer within that range. For example:

// attempt to generate an array of 10 unique shuffled numbers
// between, and including, 10 and 15
var myArr:Array = randListFromRange(10, 15, 10);
trace(myArr); // outputs 10, 11, 12, 13, 14, 15

1 comment:

Anonymous said...

This is great!

Thanks!