Recipe 5.7 Generating a Random Number

5.7.1 Problem

You want to generate a random number within a certain range.

5.7.2 Solution

Use Math.random( ) as the basis for a custom randRange( ) method.

5.7.3 Discussion

You can use the Math.random( ) method to generate a random floating-point number from 0 to 0.999999999. In most cases, however, programs call for a random integer, not a random floating-point number. Furthermore, you may want a random value within a specific range. If you do want a random floating-point number, you will ordinarily want to specify its precision (the number of decimal places).

Here is the basic process for generating random numbers of this type:

  1. Calculate the range difference and then add 1. For example, if you want to generate random numbers between 4 and 10, the range is 10-4 (which equals 6). To ensure an equal distribution, add 1 to this range.

  2. If you want the random number to include decimal places, multiply the range by the correct multiple of 10 prior to adding 1. For example, to create random numbers with one decimal place, multiply the range by 10. To create random numbers with two decimal places, multiply the range by 100, etc.

  3. Multiply the value from step 2 by the value returned by Math.random( ). This will give you a value between 0 and the value from step 2 (with decimal places).

  4. Use the Math.floor( ) method to get the integer part of the value from step 3.

  5. Divide the result from step 4 by the same multiple of 10 that you used in step 2. For example, if you originally multiplied by 10, divide by 10. This step converts the result to the correct number of decimal places.

  6. Add the value from step 5 to the smallest value in the range. This offsets the value to be within the specified range.

A custom Math.randRange( ) method encapsulates the process so that you can generate random numbers while blissfully ignoring the details.

The custom randRange( ) method should take up to three parameters:

minNum

The smallest value in the range.

maxNum

The largest value in the range.

decPl

The number of decimal places to which to round the random number. If or omitted, the number is returned as an integer.

Here is our custom randRange( ) method, which is attached directly to the Math object, so it is available throughout the entire movie. It assumes that minNum is always less than maxNum. You can add this custom method to the Math.as file for easy inclusion in other projects.

Math.randRange = function(minNum, maxNum, decPl) {   // Default to zero decimal places (generate a random integer).   decPl = (decPl == undefined) ? 0 : decPl;   // Calculate the range, multiply by 10 to the power of the number of decimal    // places, and add 1. We'll call this "delta".   var rangeDiff = (maxNum - minNum) * Math.pow(10, decPl) + 1;   // Multiplying delta by Math.random(  ) generates a value from 0 to 0.999 * delta.   var randVal = Math.random(  ) * rangeDiff;   // Truncate the value to the integer part.   randVal = Math.floor(randVal);   // Restore the proper number of decimal places.   randVal /= Math.pow(10, decPl);      // Add minNum as an offset to generate a random number in the correct range.   randVal += minNum;   // Return the random value. Use the custom roundTo(  ) method from Recipe 5.3 to   // ensure that the result is rounded to the proper number of decimal places.   return Math.roundTo(randVal, Math.pow(10, -decPl)); };

Here is an example of how to use the randRange( ) method, assuming it has been stored in an external ActionScript text file named Math.as:

#include "Math.as" // Generate a random integer from 5 to 10, inclusive. trace(Math.randRange(5, 10)); // Generate a random number, rounded to two decimal places from -5 to 5. trace(Math.randRange(-5, 5, 2));

You can use randRange( ) when you don't want an even distribution from 0 to the maximum value in the range. Here is an example of how to use randRange( ) to generate a random alpha value for a movie clip in the range of 75 to 100. It allows a clip to have a random alpha while avoiding clips that are too transparent.

myMovieClip._alpha = Math.randRange(75, 100);

Random numbers generated by traditional programming languages are not truly random. Rather, they are derived from a pseudorandom algorithm fed by an initial random seed. ActionScript does not allow you to specify the random seed (Flash presumably uses an essentially random starting point, such as the time in milliseconds). Don't confuse a random number with a unique number because random numbers are not guaranteed to be unique.

5.7.4 See Also

Recipe 5.3 and Recipe 5.11



ActionScript Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2005
Pages: 425

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net