


Flash Tutorial  Generating Random Numbers
Free Flash Tutorial
Step Four: Non Repeating Random Number
Most of the time you don't want a random number that is really random only nearly random! Mostly you want a random number which is non repeating. In other words every time you click on the button you want a new result not to repeat the number that is already there. Thus if my current number is 1 I want the next number to be any random number except 1.
The code that I am going to show you creates a random number and checks to see if it the same as the previous number that was generated. If it is the same it generates a new random number. Of course it could then generate the same number again so it checks this five times. Theoretically this could (and very occasionally will) generate the same number twice the statistical chance is very small. For example if i am generating a number between 1 and 10 the chance would be 1 in 100,000.
10 x 10 x 10 x 10 x 10 = 100,000
If I am generating a random number between 1 and 3 the natural repeat rate would be 1 in 3 or a very high chance. But if I run it through this simple system it increases to 1 in 243.
3 x 3 x 3 x 3 x 3 = 243
Try it and see how long you have to click before the number repeats (don't blame me if you get a sore click finger!!):
My Example: Download the Flash file Int 039b
Click to generate a non repeating random number between 1 and 3.
The ActionScript attached to the button is as follows:
on (release) {
// Sets the number of digits in the random sequence:
var mySetting = 3;// Creates a random number:
myNumber = random(mySetting)+1;// Checks to see if it is repeating itself:
while (myNumber == myTemp) {
myNumber = random(mySetting)+1;
}
// Displays the random number:
myDisplay = myNumber;
// Resets the variable to the new random number:
myTemp = myNumber;
}With Thanks: Code submitted by Alexander Kuzmin
The mySetting = 3; sets the number range. In this case it will produce a random number between 1 and 3. The variable myTemp holds the previous generated random number.

•
29778 visitors to this page since
2 July 07 •


Webwasp is Phil Schulz's baby. You are welcome to contact me or become my Facebook friend:
Click here
All material on this site is protected under international copyright © law. DO NOT reproduce any material from this site without written permission. Please ask as permission is often granted.
