3 Replies Latest reply on Dec 7, 2010 10:03 AM by kglad

unique Random numbers

How to get unique random numbers every time in AS3

I have searched but not able to get satisfactory results

• 1. Re: unique Random numbers

what's wrong with Math.random()?

the chances of getting a duplicate is pretty small.  but you could use an array to make sure if that's a concern.

• 2. Re: unique Random numbers

var rand :Number;

rand = Number(movXml.movie.length());

for(var n:uint = 0 ; n<5 ; n++)

{

num1 = Number(Math.round(Math.random()* ((rand-1) - 0) + 0 ) );

if(tempArray.indexOf(num1) == -1)

{

tempArray.push(num1);

}

//trace(tempArray);

num2  = Number (tempArray[0]);

//trace("num1:"+num2);

trace(tempArray);

}

some time this produce more than 5 numbers

and some time less than 3

I want 4 random numbers , but different

the above loop runs 4 times , so if number is repeated , it will not add to Array , hence i will not able to get 4 Required numbers

• 3. Re: unique Random numbers

use:

var tempArray:Array=[]

for(var i:uint=0;i<movXml.movie.length()){

tempArray.push(i);

}

shuffle(tempArray);

// you can now iterate through tempArray for random integers from 0 to moveXml.movie.length()-1

function shuffle(a:Array) {
var p:int;
var t:*;
var ivar:int;
for (ivar = a.length-1; ivar>=0; ivar--) {
p=Math.floor((ivar+1)*Math.random());
t = a[ivar];
a[ivar] = a[p];
a[p] = t;
}
}