Hi, I'm doing the exercise on (http://www.cplusplus.com/forum/articles/12974/) called "Bracketing Search", 4 star. I'm pretty close to what I need, but just can't get the computer to always win in under 7 tries.
#include <iostream>
#include <ctime>
usingnamespace std;
int main() {
int choice = 0;
int randnum = 0;
int hotcold = 0;
int runs = 0;
int max = 100;
int min = 1;
srand((int)time(0));
do {
cout << "\nPlease enter a number from 1 to 100 for the computer to guess: ", cin >> choice;
if (choice > 100 || choice < 1)
cout << "\nNot a number from 1 to 100.\a";
} while (choice > 100 || choice < 1);
randnum = rand() % max + 1;
do {
cout << "\nComputer chooses " << randnum << ".";
if (randnum == choice)
break;
cout << "(1)Lower or (2)Higher? ", cin >> hotcold;
switch (hotcold) {
case 1:
if (max >= randnum)
max = randnum;
randnum = rand() % (max - min + 1) + min;
++runs;
break;
case 2:
if (min <= randnum)
min = randnum;
randnum = rand() % (max - min + 1) + min;
++runs;
break;
default:
cout << "\nNot a choice.\a";
break;
}
} while (runs < 7);
if ( randnum != choice )
cout << "\nYou win!";
else
cout << "\nComputer wins!";
cin.ignore(2);
return 0;
}
Make computer pick the number that is in the middle of available pool of numbers to minimize the number of retries. The rule is to win in 7 or less, so seven is ok.