Code Tip: Array containing random but unique numbers

I am just sharing here a good utility function I found over the internet to get an array of random but unique numbers starting from zero.

Here it is:

function getUniqueRandom ( range:int ):Array
{
var numberList :Array = [];
var randomList :Array = [];
var i :int;

for ( i = 0; i <= range; i ++ )
{
numberList[ i ] = i;
}

var length :int = numberList.length;

for ( i = length - 1; i >= 0; i -- )
{
var picked = Math.floor ( Math.random () * i );
randomList[ i ] = numberList[ picked ];
numberList[ picked ] = numberList[ i ];
}

return randomList;
}

example:
var myArray :Array = this.getUniqueRandom ( 10 );
trace ( myArray ) // results: 5,1,4,7,10,2,3,9,6,8,0

Advertisements
Code Tip: Array containing random but unique numbers

One thought on “Code Tip: Array containing random but unique numbers

  1. I should have been a little more careful before posting/pasting any code in a blog because apparently some of the ActionScript symbols are omitted but I found a workaround.

    Anyways, the code above in the blog-post is now updated with a working version.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s