printGuesses
Category: Programming
Author: Benson Limketkai
Book Chapter: 5.2
Problem: printGuesses
In the number-guessing game, you are to guess a number between 1 and 100. After each guess, you are given a hint as to whether your guess is higher or lower than the actual number. Your goal is to guess the actual number with as few guesses as possible. Consider how you would play such a game. The optimal strategy would make an initial guess of 50, because it is halfway between 1 and 100. The first hint would indicate whether 50 was higher or lower than the actual number. Using that information, the optimal strategy can arrow the interval of numbers to consider: If 50 is higher than the actual number, then the actual number is in the interval between 1 and 49. The optimal player would then guess 25, which is halfway between 1 and 49. If 50 is lower than the actual number, then the actual number is in the interval between 51 and 100. The optimal player would then guess 75, which is halfway between 51 and 100. After each guess, the optimal strategy continually halves the size of the interval in which to make guesses until the answer is reached. Write a static method named printGuesses that accepts the actual number (an integer) and prints the series of guesses that would be made by an optimal player. The guesses are separated by commas. Here are some example calls to your method and their expected results: Call | Output ---------------------------------------------------- printGuesses(34); | 50, 25, 37, 31, 34 printGuesses(1); | 50, 25, 12, 6, 3, 1 printGuesses(82); | 50, 75, 88, 81, 84, 82 printGuesses(50); | 50 printGuesses(100); | 50, 75, 88, 94, 97, 99, 100