I'm down to the Bracketing Search exercise and have coded the bot to answer in 10 or less tries, but I can't get the bot to guess in 7 tries or less each time, as is part of the exercise.
#include <iostream>
#include <cstdlib>
#include <ctime>
using std::cout, std::cin;
using std::rand, std::srand;
int main() {
int min {1};
int max {100};
int botGuess {0};
int secretNumber{54}; // hard-coded number for the bot to guess
int guesses{0};
int range{0};
cout << "I'm thinking of a number between 1 and 100.\n";
srand(time(nullptr));
do {
cout<< "Your guess: ";
range = (max - min) + 1;
botGuess = rand() % range + min;
cout<< botGuess;
++guesses;
if (botGuess > secretNumber) {
cout << "\nToo high!\n";
max = botGuess - 1;
} elseif (botGuess < secretNumber) {
cout << "\nToo low!\n";
min = botGuess + 1;
}
} while (botGuess != secretNumber);
cout<< "\nWell done, bot!\n";
cout << "Took you " << guesses << " tries to guess " << botGuess << '\n';
return 0;
}
So what can I do to make the bot guess in 7 tries or less?
guessing games are just a twist on the binary search.
100 is max.
pick 50. 1*
its higher or lower, 54 is higher, pick 150/2 = 75 *2
75 is too high, (50+75)/2 is 62. too high. *3
50+62 / 2 is 56 *4, too high. 50+56/ 2 is 53 *5, too low. 53+56... 54 got it. *6 guesses.
its ensures to win in 7 tries, 2^7 is 128 which > 100. But its boring, it will guess the same first few values (eg 50, 25 or 75, ..) every time: its not a guessing game at that point, its an optimal solution.
@jonnin - Thank you for showing me what I asked for. I found this to be a nice challenge. So it served its purpose, in that regard. And cire's post made rand() more clear. Thanks for your explanation. Easy to see what you're talking abt.