Code Snippets: Generating a Random Number for Flash ActionScript 3 (AS3)

Generating a random number for use in Flash is a common problem that many developers come across. Luckily the Math object provides static methods to help us perform this basic task.  Found below are two snippets of how to generate a random integer from 0 to a max number or for a range of values.

How to Generate a random number from 0 to a max value:

Math.floor( Math.random() * (maxNum + 1) );

Examples:

Problem – return a number between 0 and 10

Math.floor( Math.random() * 11 );

Problem – return a number between 0 and the length of an array

Math.floor( Math.random() * myArray.length );

How to Generate a random number between the range min and max inclusively:

Math.floor( minNum + 
     (Math.random() * (maxNum - minNum + 1) ) );

Examples:

Problem – return a number between 10 and 45

var minNum = 10;
var maxNum = 35;
Math.floor( minNum + ( Math.random() * (maxNum - minNum + 1 ) ) );
//-- Math.floor( 10 + (Math.random() * 26) );

Code Break Down:

In the two methods we used the Math.random() and Math.floor() functions to generate our random number for us. The Math.random() function returns a value between 0 and 1 with 1 excluded. While the Math.floor() function returns the whole number or integer below the current value ( e.g. Math.floor( 3.82 ) = 3 ).  Utilizing these methods we generate a number in the desired range by multiplying the random number generated by our max value + 1 as the floor function will only return a value of max value.

// Code Snippets // Flash //

Comments & Questions

  1. Are you still using protected fields when they should be private? 😀

    1. of course !! bad habits never seem to go away.

Add Your Comment