5.8. Simulating a Coin Flip
Problem
You want to simulate a coin flipping or other Boolean (true/false) event in which there is a 50% chance of either outcome.
Solution
Use the randRange( )
method to generate an
integer that is either 0 or 1 and then correlate each possible answer
with one of the desired results.
Discussion
You can use the randRange( )
method from
Recipe 5.7 to generate a random integer in
the specified range. To relate this result to an event that has two
possible states, such as a coin flip (heads or tails) or a Boolean
condition (true or false), treat each random integer as representing
one of the possible states. By convention, programmers use 0 to
represent one state (such as “off”)
and 1 to represent the opposite state (such as
“on”), although you can use 1 and 2
if you prefer.
For example, here is how you could simulate a coin flip:
#include "Math.as" function coinFlip ( ) { flip = Math.randRange(0, 1); if (flip == 0) { return "heads"; } else { return "tails"; } } // Example usage: trace ("The result of the coin flip was " + coinFlip( ));
Here, we write a function that tests our coinFlip(
)
routine to see if it is reasonably even-handed. Do you
expect a perfect 50/50 distribution regardless of the number of coin
flips? Test it and see.
#include "Math.as"
function testCoinFlip (numFlips) {
// We'll count how many of each result occurs. Initialize them to 0.
var heads = 0;
var tails = 0;
// Repeat the process numFlips
times and keep tabs on the results. for (var ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.