I have just written a solution to the following problem:
We all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input and great code!
I would like suggestions on how I can make my solution less complicated and if there is a more efficient way to solve the problem.
Here is my implementation. I have tried to implement a binary search strategy to solve the problem.
public class Guesser
{
private List<int> _possibleAnswers = new List<int>();
private bool _isCorrectNumber = false;
private bool _higher = false;
private int _numberOfGuesses = 0;
private int _answer;
public Guesser(int min, int max)
{
for (var i = min; i <= max; i++)
_possibleAnswers.Add(i);
}
public void Guess()
{
while (!_isCorrectNumber)
{
var middleOfAnswers = _possibleAnswers.Max() - (_possibleAnswers.Count / 2);
Console.WriteLine("Is the number {0}?", middleOfAnswers);
var hint = Console.ReadLine().ToLower();
_isCorrectNumber = hint.Equals("yes");
if (_isCorrectNumber)
{
_answer = middleOfAnswers;
continue;
}
_higher = hint.ToLower().Equals("higher");
if (_higher)
{
var count = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers)) + 1;
_possibleAnswers.RemoveRange(0, count);
}
else
{
var startIndex = _possibleAnswers.FindIndex(guess => guess.Equals(middleOfAnswers));
var count = _possibleAnswers.FindIndex(guess => guess.Equals(_possibleAnswers.Max())) - startIndex + 1;
_possibleAnswers.RemoveRange(startIndex, count);
}
_numberOfGuesses++;
}
Console.WriteLine("The number was {0} and it took me {1} guess{2}",
_answer, _numberOfGuesses, _numberOfGuesses > 1 ? "es" : string.Empty);
}
}
Any suggestions on how I can improve this would be great. I'd also like to know if I have understood the concept behind a binary search and implemented it correctly.