[Snippet] Get array of (non-repeated) random Numbers.

I’ll save my story because of bleh.

Given a range, get N numbers (within that range) without repeating one.

Example:

Numbers wanted: 3.

From range : 8 – 23.

Result: 10, 19, 8.

private function getRandomNumbers(low:Number, high:Number, howMany:Number):Array
{
var store:Array = [];

if (howMany > high)
{
trace(“too many numbers wanted, howMany must be less or equal to high”);
return store;
}

while (store.length < howMany)
{
var randNum:Number = Math.floor(Math.random() * (1 + high – low)) + low;

if (store.indexOf(randNum) == -1)
{
store.push(randNum);
}

}

return store;
}

Isn’t non-formatted code a thing of beauty?

Usage:

var min:Number = 5;
var max:Number = 20;
var howMany:Number = 6;

var rNums:Array = getRandomNumbers(min, max, howMany);

Kinda lame alghoritm, I’m not very good at math and logic (and somehow I am a programmer), but there it is.

Update (1 day later): thanks to @sophistifunk for pointing me to use indexOf, so I saved some lines 🙂