7 Replies Latest reply on Oct 16, 2007 7:38 AM by Greg Dove

# Array with unique random numbers

Hi,
I'm trying to come up with a function that will populate an array with 4 unique random numbers. I'm stuck on pushing unique numbers, the attached code creates the array, but sometimes there are duplicate numbers. I've tried a for staement inside the for stement to test for duplicates but get lost. Is there an easy way to do this? Thanks.

• ###### 1. Re: Array with unique random numbers
To do what you want you make a temp array: [1,2,3,4,5,6,7,8] - then you
pull from that array at random locations and delete at that index... do that
four times and you have your random array.

--
Dave -
http://www.blurredistinction.com

• ###### 2. Re: Array with unique random numbers
Hi Rob ,

Please check this ...it is my first time reply on this site :)

• ###### 3. Re: Array with unique random numbers
Thanks! The i = i-1; is a very cool trick.
• ###### 4. Re: Array with unique random numbers
This will work:

function makeRandomArray(startVal:Number, endVal:Number,
numElements:Number){
var temp:Array = new Array();
var rand:Array = new Array();
for(var i = startVal; i <= endVal; i++){
temp.push(i);
}
for(var i = 0; i < numElements; i++){
var ind = Math.floor(Math.random() * temp.length);
rand.push(temp[ind]);
temp.splice(ind,1);
}
return rand;
}

trace(makeRandomArray(1,8,4));

--
Dave -
http://www.blurredistinction.com

• ###### 5. Re: Array with unique random numbers
>>Thanks! The i = i-1; is a very cool trick.

i--; is cooler...

--
Dave -
http://www.blurredistinction.com