Random numbers / array elements

Random number within a specified range

The function

Just use this simple function:

private function randomRange(minNum:Number, maxNum:Number):Number  
{ 
    return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum); 
} 

Testing example

Use some traces function to test the function:

var randomNum:Number = randomRange( 10, 20 );
trace(randonNub); // traces 16
trace(randonNub); // traces 12
trace(randonNub); // traces 19

var randomNum:Number = randomRange( -5,5 );
trace(randonNub); // traces -2
trace(randonNub); // traces 3
trace(randonNub); // traces 4

Learning Resources

  • Get a Random Number Within a Specified Range Using AS3 tutorial.

  • How to Randomly Shuffle an Array in AS3 tutorial.

 

Post A Comment

Anti-Spam Quiz: