I enjoy playing number games. I’m not good at it, but I enjoy playing them. Recently such a game piqued my curiosity enough to consider it for my monthly *C For Dummies* exercise: 21

No, not the card game 21, also known as Blackjack. This is a counting game:

Each player states a number between 1 and 3 to be added to a running total. Player One guesses 2, then Player Two adds 3 to make 5, and so on up to 21. The first player to arrive at 21 either wins or loses, depending on the game variation.

I coded this number game and will present it in a future Lesson. But wanting to cheat, I did some research to discover whether any magic exists behind winning the game.

The immediate thing I discovered, assuming the desire is to reach (not avoid) 21, was that whoever gets to 18 first loses. Once you hit or just pass 18, the next player can add 1, 2, or 3 to reach 21. You can wind back this value to try to figure where the first magic number is, after which you can follow a pattern to win the game. I didn’t bother pursuing this approach further.

Later, I read that it’s possible to win providing you go second and add values so that the result is a multiple of 4. For example, if the other player guesses 3, you guess 1 to make 4. If they guess 6, you guess 2 to make 8. And so on.

Anyway.

It turns out the multiple-of-four trick didn’t work. Still, I was intrigued enough to code a simulation of this process, which is this month’s Exercise.

Your task is to write code that pits two players against each other. Call them “player” and “computer.”

Starting with a total value of zero, the “player” goes first and selects a random value between 1 and 3. The “computer” goes next, adding a random value between 1 and 3 — but ensuring that the total is evenly-divisible by 4. This process repeats until the total value is over 30.

Here’s sample output:

`Player adds 2, total is 2`

Computer adds 2 to make 4

Player adds 1, total is 5

Computer adds 3 to make 8

Player adds 2, total is 10

Computer adds 2 to make 12

Player adds 3, total is 15

Computer adds 1 to make 16

Player adds 2, total is 18

Computer adds 2 to make 20

Player adds 3, total is 23

Computer adds 1 to make 24

Player adds 3, total is 27

Computer adds 1 to make 28

Player adds 2, total is 30

Computer adds 2 to make 32

No matter what the “player” guesses, the “computer” adds 1, 2, or 3 to make the total a multiple of 4: 4, 8, 12, 16, 20, 24, 28, and finally 32.

Sure, this is a silly exercise (aren’t they all?), but it’s how I was able to determine the multiple-of-four trick couldn’t guarantee a win for my 21 number-guessing game.

Try this Exercise on your own before you peek at my answer, which I’ll post in a week.