|
|
Click to generate a new set of numbers
|
||||
|
||||
|
||||
Somebody on Were Here asked how you could generate a series of random numbers without repeating the same number. The obvious solution is to go through all generated numbers each time, checking to see if the new number has already appeared. If it has, you generate another...and keep going until you get however many you need. However, this is extremely inefficient -- the amount of checking for even a small number of values is prohibitive -- and leaves the possibility of getting stuck in almost never-ending loops.
So I thought about it and came up with this method, which probably isn't a new idea but I've never seen it before. You'll find an .fla in zip form of the above file here, and a version with the randomising code only here (this is the version I refer to below).
Let's say you want five unique random numbers between 1 and 5. Obviously just generating five random numbers won't work -- the same number will almost certainly appear more than once. So instead, we create a series of variables (an array, in fact) of all possible values -- in this case, 1, 2, 3, 4, 5. These variables (var1 to var5) are created in this loop:
Set Variable: "number" = 5
Set Variable: "counter" = 1
Loop While (counter <= number)
Set Variable: "var"&counter = counter
Set Variable: "counter" = counter + 1
End Loop
Now we do the random bit. First we start a loop that counts down from the number of random numbers we want (in this case, five) to two. Next, we generate a random number random_number between one and our maximum number (in this case, five). We get the value of the variable corresponding to our new random number, and place it in a new variable "random"&counter. Now, we remove that 'used' variable from the array, by replacing it with the last 'unused' value. Finally we reduce counter by one, and restart the loop. Once the loop is done, we assign the remaining value of the var array to random1.
Set Variable: "counter" = number
Loop While (counter > 1)
Set Variable: "random_number" = (Random (counter )) + 1
Set Variable: "random"&counter = eval("var"&random_number)
Set Variable: "var"&random_number = eval("var"&counter)
Set Variable: "counter" = counter - 1
End Loop
Set Variable: "/random1:value" = var1
To make it clearer: here's a possible series of events:
Loop 1: counter = 5
Loop2: counter = 4
and so forth.
So each time we 'use' one of the values stored in the array (var1 to var5), we remove it by replacing it with the value of the last remaining element of the array -- in the first loop that would be var5, in the second loop var4, in the third loop var3...you get the idea.
You're probably right.
Good luck!
All files and text copyright ©Stickman 1998 - 2003. For copyright and terms of use information, please read this page.