### Bracketing Search

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.

Tips?

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657`` ``````#include #include using namespace 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; }``````
Last edited on
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.
 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556`` ``````#include int main() { int results[100]; for(int goal = 1; goal <= 100; goal++){ int min = 1; int max = 100; int last = 50; int poolSize = 100; std::cout << "Goal: " << goal << " \t"; int nTries = 1; std::cout << "Guessing: "; while(true){ std::cout << last <<", "; if(last == goal){ std::cout << "\n (" << nTries << " tires.)\n"; break; } else if(last > goal) { max = last; poolSize = max - min; last = min + floor(poolSize / 2.0); //half rounded down } else if(last < goal) { min = last; poolSize = max - min; last = min + ceil(poolSize / 2.0); //half rounded up } nTries++; } results[goal-1] = nTries; } int timesPerTryCount [10] = {0}; int mostTries = 0; for (int i = 0; i < 100; i++){ if(mostTries < results[i]){ mostTries = results[i]; } timesPerTryCount[results[i]]++; } std::cout << "\nGuessed in\n"; for(int i = 1; i < 10; i++){ if(i == 1) std::cout << i << " try:\t\t"<< timesPerTryCount[i] << " times\n"; else std::cout << i << " tries:\t"<< timesPerTryCount[i] << " times\n"; } std::cout << "\nMost number of tries: " << mostTries; std::cout << "\n\nHardest to guess:\n"; for(int i = 0; i < 100; i++) { if(results[i] == mostTries) std::cout << i+1 << ",\t"; } while(1); }``````
Last edited on
I figured that's what I had to do, but I thought that might be cheating haha. I'll try my own approach and see what I can do.

Thanks
Topic archived. No new replies allowed.