Coin Flipping Madness!

Difficulty: ★ ★ ☆ ☆

Probability. Odds. These are words I often confuse, but the similarity relates to how often things happen. The gold standard is the flip of a coin: two possibilities, heads or tails. If you don’t understand how it works, you can write code to drive home the point.

In C, you use the rand() function to generate a random value. Couple the output with a modulus expression and you end up with values either one or zero. From this result you can interpret that zero is “heads” and one is “tails” — or vice-versa. It truly doesn’t matter.

According to the people in white lab coats, no matter how often you flip a coin, the probability of it landing heads up or tails up is always the same, one chance in two; the odds are “even.” Yeah verily, even if you flip a coin ten times and each time it comes up heads, the next flip still has an even chance of being heads or tails.

For this month’s Exercise, your challenge is to write code that simulates a coin flip. Flip the coin 100 times, outputting the total tally like this:

44 Heads, 56 Tails

But wait! There’s more . . .

Have the program perform 100 sets of 100 coin flips. Something like this:

Set   1: 43 Heads, 57 Tails
Set   2: 49 Heads, 51 Tails
Set   3: 51 Heads, 49 Tails
Set   4: 54 Heads, 46 Tails
Set   5: 48 Heads, 52 Tails
.
.
.
Set  97: 50 Heads, 50 Tails
Set  98: 63 Heads, 37 Tails
Set  99: 58 Heads, 42 Tails
Set 100: 64 Heads, 36 Tails

Then, once the 100 sets of 100 flips are complete, the program outputs details about all the flips. Here are the final lines from my solution:

Results from 100 sets of 100 flips:
Overall average: 50.0 Heads, 50.0 Tails
Number times it was 50/50: 15
Greatest number of heads: 61
Greatest number of tails: 61

These details show the overall average of all the sets, total of heads and tails. Above it’s 50:50, but this isn’t always the case!

The output must also describe the number of times the 100 flips yielded a perfect 50:50 split between heads and tails.

Finally, output the greatest number of heads and tails for all of the sets. Above, weirdly, one of the sets had 61 heads (and 39 tails) and another had the opposite. Again, these numbers don’t always work out evenly. I’ve run my solution several times to see how things turn out. Yes, only with a computer can you flip a coin 10,000 times and view the results in a matter of nanoseconds.

Please try this Exercise on your own before you peek at my solution.

Leave a Reply