Last month, I published a post of the classic programming chestnut, a number-guessing game. In the post, I wrote: “Variable
tries is set equal to 6 because I read somewhere that it’s possible to guess a value between 1 and 100 in six or fewer tries (though I’m probably incorrect).” And, yes, I was wrong.
The true value is seven: When using logic, it takes a maximum of 7 attempts to accurately guess a random value between 1 and 100 (inclusive). This generality got me thinking: If you apply logic to a number-guessing game, you follow a set rule to figure out which number to guess. The rule, or algorithm, works like this:
- Divide the range of numbers by two and guess that number (lowest valid number + ½ × range)
- If the guess is correct, game over, otherwise:
- If the guess is high or low, split the range accordingly and repeat at Step 1.
For example, you first guess 50. The computer says, “Too low!”
You split the difference: 50 to 100 and guess 75. The computer says, “Too high!”
You split the difference again: 50 to 75 and guess 63.
And so on.
Your task for this month’s Exercise is to code this logic: Have the computer generate a random value between 1 and 100. Based on the range, have the computer guess the random value by splitting the difference. The guess is then reported as too high to too low. Repeat the process until the number is discovered, then report how many guesses it took.
Here is a sample run of my solution:
Generating a random number 1 to 100... Try Number Guess Result #1 78 50 v low #2 78 75 v low #3 78 87 ^ high #4 78 81 ^ high #5 78 78 Correct
Above, the computer generated random value 78. It took the computer 5 tries to come up with the correct value.
Click here to view my solution. Before you peek at what I’ve done, please try this Exercise on your own. And run the test several times to confirm that seven is the maximum number of tries it takes to logically guess a random value between 1 and 100.