5 Replies Latest reply on Nov 17, 2010 7:10 AM by xxxheeroxxx

# generate non duplicating random number from a range of values

Good day people,

I need help again. I want to animate an image inside a movieclip with frame label animate1, animate2, animate3 and animate4.

I did manage to generate random numbers but my concern is that I want my animation will not animate same image twice, below is my code.

==== code in main time line ====

function randRange(min:Number, max:Number):Number {
// Generate a number between and including min – max
var randomNum:Number = Math.floor(Math.random()*(max-min))+min;
return randomNum;
}

//build array to hold frame label names
var frameArray:Array = new Array();
frameArray[0] = "animate1";
frameArray[1] = "animate2";
frameArray[2] = "animate3";
frameArray[3] = "animate4";

// Get random number created
var n:Number = randRange(0, frameArray.length);

trace("n: " + n);

// gotoAndStop Frame label name
this.img_ani.gotoAndStop(frameArray[n]);

trace("frameArray: " + frameArray[n])

==== code and frame label inside a movie clip with 4 frames containing different images ===

as layer: stop();

frame label: animate1, animate2, animate3, animate4

Any help is greatly appreciated. Thanks in advance.

• ###### 1. Re: generate non duplicating random number from a range of values

Rather than randomly picking one each time, you can just shuffle the array at the start and go thru it in order.

• ###### 2. Re: generate non duplicating random number from a range of values

I did'nt know there is a shuffle function in Arrays.

Any ideas on how to apply it in my code...

I just realize I'm still newbie in flash. /wew

• ###### 3. Re: generate non duplicating random number from a range of values

There isn't a built-in shuffling routine, but there is a fairly standard shuffle function that gets passed around...

var frameArray:Array = new Array();
frameArray[0] = "animate1";
frameArray[1] = "animate2";
frameArray[2] = "animate3";
frameArray[3] = "animate4";

function shuffle(a) {
var p;
var t;
var ivar;
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;
}
}

trace(frameArray);  // show before shuffle

// Usage:
shuffle(frameArray);

trace(frameArray);  // show after shuffle

• ###### 4. Re: generate non duplicating random number from a range of values

Thanks Sir Ned for the work around the code.

Just googled the shuffle in array and have a bunch of shuffle function.

More power... Thanks

• ###### 5. Re: generate non duplicating random number from a range of values

You're welcome