|
|
|
||||
|
||||
Thought I'd update my unique random number generator for Flash 4 using native Flash5 code. There's nothing very new in it, but it runs faster than the F4 code (I've had it handle up to 40,000 random numbers in one pass). Here's the .fla file in .zip form
As with the Flash4 version, it works by creating an array of all the possible values in order, then picks them one by one and places them in a new array. It then takes the last 'unused' value and inserts it in place of the 'used' value, and reduces the number of values left to be picked by one.
Here's the code, which you'll find in the actions of the first frame of the movie:
function getUniqueRandom (number) {
var numberlist = new array();
for (count = 1; count <= number; count++) {
numberlist[count] = count;
}
this.randomlist = new array();
for (count = numberlist.length - 1; count > 0; count--) {
picked = math.floor(math.Random()*count)+1;
this.randomlist[count-1] = numberlist[picked];
numberlist[picked] = numberlist[count];
}
return randomlist;
}
To call the function, just use the following code:
x = new getUniqueRandom(10);
The label 'x' can be anything you like, and the number in brackets is the number of random values you require. What you get is an array x.randomlist[], of the randomised numbers. To get to the first value (for example) you'd use the following code:
firstnumber = x.randomlist[1] secondnumber = x.randomlist[2]
...and so on for as many random values as you need.
Briefly, it works like this. First, we create an array (numberlist) which contains a sequential list of numbers from 1 to the number we sent -- so if we asked for 100 unqiue random numbers, we get an array which goes 1,2,3...98,99,100.
Then we create another array (randomlist). Now we execute a loop, which each time picks a random number between 0 and the number of elements in our numberlist array. We then copy the value in that entry in the numberlist array into the next 'slot' in our random array. Finally, we copy the last remaining value in the numberlist array into the slot of the number we just picked -- this reduces the number of available values in the numberlist array by one (because the one we just picked is no longer available to be picked).
If you're confused, take a look at the code in the .fla file, which features plenty of comments. Also, you could read the original version which has more explanation as to how the technique works (although it uses different syntax, it works the same way).
I tried this method originally, but it was very slow indeed. I found that the rather less elegant method above is much faster. So there.
Good luck!
All files and text copyright ©Stickman 1998 - 2003. For copyright and terms of use information, please read this page.