Automated Guessing Game – Solution

In the climatic scene of the movie Wargames, the WOPR computer plays Tic-Tac-Toe. A question is asked, “Can the computer play itself?” This postulation forms the basis of all computer learning, but that wasn’t the puzzle for this month’s Exercise.

No, the challenge was for the computer to generate a random number between 1 and 100 and then attempt to guess the number generated. Coding in a cheat would be simple, but the point was to see how many times it takes a computer, using logic, to guess the correct value.

The magic number is seven, though I hope you ran your solution enough to see the occasional quicker guess. In fact, in one of my test runs, the random number was 50 and the computer guessed it immediately!

For my solution, I use three int variables:

guess_high is the value on the high range of the scale of possible numbers. It starts with the MAX defined constant, set to 100.

guess_low is the low range value, which starts at 1.

guess_current is calculated as: (guess_high - guess_low)/2 + guess_low The result is the value midpoint between the guess_high and guess_low values — a good guess.

After calculating the guess, a comparison is made:

if( number==guess_current )
{
    puts("Correct");
    break;
}

If the value of number, the computer’s original random number, is equal to the value guessed, guess_current, an endless loop is broken and the program exits. Otherwise an if-else structure resets the variables guess_high or guess_low:

/* output results if the guess is wrong */
if( number < guess_current ) 
{
    puts("^ high");
    /* adjust high value */
    guess_high = guess_current;
}
else
{
    puts("v low");
    /* adjust low value */
    guess_low = guess_current;
}

And the loop repeats.

Here’s a sample run:

Generating a random number 1 to 100...
Try	Number	Guess	Result
#1	68	50	v low
#2	68	75	^ high
#3	68	62	v low
#4	68	68	Correct

To view the full code for my solution, click here (GitHub). Keep in mind that mine is only one of an infinite range of possibilities. Providing that your solution also completes the task, using logical guesses to find the random number by, consider that you passed the challenge.

Leave a Reply