[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.


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)


return store;

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


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 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s