Today I had this little problem. I needed to generate a random number from 1 to 30 and the result had to except a specific number (as in this example, any number from 1 to 30 except the number 7 )

The code is done now, it’s working as it should and I posted it in case someone else needs this same code.

var randomNumber:Number;
var minNumber:Number = 1;
var maxNumber:Number = 30;
function generateRandomNumber():void{
randomNumber = Math.round(Math.random() * (maxNumber - minNumber)) + minNumber;
if(randomNumber == 7){
generateRandomNumber();
}
trace(randomNumber)
}
generateRandomNumber(); |

var randomNumber:Number;
var minNumber:Number = 1;
var maxNumber:Number = 30;
function generateRandomNumber():void{
randomNumber = Math.round(Math.random() * (maxNumber - minNumber)) + minNumber;
if(randomNumber == 7){
generateRandomNumber();
}
trace(randomNumber)
}
generateRandomNumber();

By the way, the code here is ActionScript 3 but if you remove “:void” you can use it in ActionScript 2 too 😉

### Like this:

Like Loading...

//AS 3 version- just a little cleaner piece of code.

var randomNumber:Number = generateRandomNumber(1, 30);

function generateRandomNumber(p_max:Number, p_min:Number):Number {

var randomNumber = (Math.random() * (p_max – p_min)) + p_min | 0;

if(randomNumber == 7){ return generateRandomNumber(p_max, p_min); }

return randomNumber;

}

trace(randomNumber);

JohnnyG’s Code dind’t work in my computer, so I think the code should be:

//AS 3 version- just a little cleaner piece of code.

var randomNumber:Number = generateRandomNumber(1, 30);

function generateRandomNumber(p_max:Number, p_min:Number):Number {

var randomNumber = Math.round(Math.random() * (p_max – p_min)) + p_min;

if(randomNumber == 7){

return generateRandomNumber(p_max, p_min);

}

return randomNumber;

}

trace(randomNumber);

Thanks JohnnyG!

What didn’t work about it?

Do you know what | 0 does? – (if floors your value)

what value did you get back? what values did you feed it.

You would have supply more information then … it didn’t work on my computer.

7 is not a random number.

You are a genius!