PDA

View Full Version : Help with Validating Random Numbers


george_gaz
08-13-2008, 03:08 PM
Hello,

OK the basic jist of my code is that I am creating three different random numbers between 0 and 9 (n1, n2, n3).
I took the random number code straight from the Flash help documentation because it is exactly what I needed.

Now, what I need to do is have some code that basically says "if n1 == n2 or n2 == n3 or n1 == n3 then run function again until the numbers are all different"

Here is the code I have so far for the random numbers:


//CREATING THE RANDOM NUMBERS
function randRange(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random()*(max-min+1))+min;
return randomNum;
}
for (var i = 0; i<1; i++) {
var n1:Number = randRange(0, 9);
var n2:Number = randRange(0, 9);
var n3:Number = randRange(0, 9);
}


I am just not sure how to make it re-run the function until all three numbers are different because at times I might get n1 = 1, n2 = 8, n3 = 8 but need them all to be different ;)

DiamondDog
08-13-2008, 07:21 PM
Try this:
//CREATING THE RANDOM NUMBERS
function randRange(min:Number, max:Number):Number {
var randomNum:Number = Math.floor(Math.random()*(max-min+1))+min;
return randomNum;
}

var n1:Number = randRange(0, 9); // (don't need the 'for' loop)
var n2:Number = randRange(0, 9);
var n3:Number = randRange(0, 9);


while (n1==n2 || n2==n3 || n1==n3) // if they're not all different, try again
{
n1 = randRange(0, 9);
n2 = randRange(0, 9);
n3 = randRange(0, 9);
}

trace(n1, n2, n3); // 5,4,1 etc

george_gaz
08-14-2008, 09:30 AM
Hi Diamond,

Many thanks for returning with that code. A friend of mine recommended while loops, which I had not really used before and to be honest was not too sure WHY to use one. This example has really helped me figure out just how useful they are.

Thanks very much!