Furthering a CPlusPlus Exercise

I found these exercises through a search: https://www.cplusplus.com/forum/articles/12974/

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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;
        } else if (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?

btw: thank to cire for the excellent explanation of rand(), found here https://www.cplusplus.com/forum/beginner/85134/
Last edited on
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.
Last edited on
@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.

cire's post made rand() more clear.

Perhaps you should read it again.
range should be set to max - min + 1, not just max.
Think about what would happen if min wasn't 1.
Got it covered in Line 22. But I did change Line 15

int range = max; // busy busy busy and not paying attention.

to

int range{0};

Since I was only initializing range with max, it all worked out. Sure didn't look right, though. Thanks for spotting that.
Last edited on
Topic archived. No new replies allowed.