12.3. Using Random Numbers

If we want to simulate something like flipping a coin, we can assign a different number to each possible outcome. There are two sides to a coin - heads and tails - so let’s call heads 0 and tails 1. If we make a random integer between 0 and 1, we can think of it as representing heads or tails on the coin:

By using the accumulator pattern and a loop, we could repeat a series of flips. Let’s do 100 flips and count up how many are heads (0). Each time through the loop, we will pick a new random number. We will only add to our accumulator numHeads if the random value is 0.

Try running the program a few times. You usually won’t get exactly 50, but it will usually be pretty close to that number since we flip 100 coins. Determining if this program is working correctly is a bit of a challenge - it would take too long to use Codelens to watch the whole execution. To sanity check it, try the following:

Note

Remember that while debugging we should simplify things as much as possible and use print statements to “see” what is happening as our code runs.

Mixed up programs

The following program should roll 10 dice (that have sides from 1-6). We want to count print the number of dice that show a 6. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly! You will not use all of the blocks.

You have attempted of activities on this page