In: Computer Science
In C++
Task 2B: User picks an integer in a range and computer guesses using approach similar to binary-search
Enter the left end and right end of a range of integers. User chooses an integer in that range. Computer makes a guess that equals the mid of the range. User gives a feedback for each guess: 1 for too big, 2 for too small and 3 for just right. When the feedback is 1 (too big), the computer throws away any integer that is bigger than guess. When the feedback is 2 (too small), the computer discards the integers any integers that is smaller than the guess. When computer makes a correct guess, the game ends.
Note that your code must ensure a user to entre a feedback in [1, 3].
Sample input/output:
Enter left end in range: 0
Enter right end in range: 10
User has an int in [0, 10]. Computer will guess.
guess #1: 5. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 2
guess #2: 8. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 1
guess #3: 6. How is my guess?
1. too big 2. too small 3. just right
Enter only 1, 2, or 3: 2
guess #4: The answer must be 7.
#include <iostream>
using namespace std;
int main()
{
int left, right;
// read left
cout << "Enter left end in range: ";
cin >> left;
// read right
cout << "Enter right end in range: ";
cin >> right;
cout << "User has an int in [" << left << ", " << right << "]. Computer will guess.\n";
int i = 1, guess, feedback;
// loop till guess is correct
while (true)
{
guess = (left + right) / 2;
// print guess
cout << "guess #" << i << ": " << guess << ". How is my guess?\n";
cout << "1. too big 2. too small 3. just right\n";
cout << "Enter only 1, 2, or 3: ";
cin >> feedback;
// if too big
if (feedback == 1)
{
if (guess == left + 1)
{
cout << "guess #" << i + 1 << ": The answer must be " << left << ".\n";
break;
}
right = guess - 1;
}
// if too small
else if (feedback == 2)
{
if (guess == right - 1)
{
cout << "guess #" << i + 1 << ": The answer must be " << right << ".\n";
break;
}
left = guess + 1;
}
// else if guess is correct
else
{
break;
}
i++;
}
return 0;
}
.
Output:
.