# Ai?

• 11-18-2005
Drake
Ai?
I was wondering how i would go about and make an AI that actually guesses a number that i pick by whether i say "Too high" or "Too low".
Here is an example of code from a guessing game.

Code:

```// Guess My Number // The classic number guessing game #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() {         srand(time(0)); // seed random number generator         int theNumber = rand() % 100 + 1; // random number between 1 and 100         int guess= rand() % 100 + 1;//Computer guesses number between 1 and 100         int tries = 0;             cout << "\tWelcome to Guess My Number\n\n";         do         {                 cout << "Enter a guess: "<<guess;                 ++tries;                 if (guess > theNumber)                         cout << "Too high!\n\n";                 if (guess < theNumber)                         cout << "Too low!\n\n";         } while (guess != theNumber);         cout << "\nThat's it! You got it in " << tries << " guesses!\n";                 system("pause");     return 0; }```
• 11-18-2005
Quantum1024
Have the AI guese by generating random numbers. After each guese ajust the min or max random number values.
• 11-18-2005
sand_man
So you want to make a game that's impossible to win? :p
• 11-18-2005
SlyMaelstrom
Code:

`int guess= rand() % 100 + 1;//Computer guesses number between 1 and 100`
Like this:

Code:

```int maxVal = 100; int minVal = 1; do{   guess= rand() % maxVal + minVal;  // This has to be in the loop.   cout << "Enter a guess: "<<guess;   ++tries;   if (guess > theNumber) {     cout << "Too high!\n\n";     maxVal = guess - minVal;     }   else if (guess < theNumber) { // Else if cause there is no point in checking both.     cout << "Too low!\n\n";     minVal = guess;     maxVal = maxVal - minVal;     } } while (guess != theNumber);```
My math appears to be a little messed up with the too low, but you get the idea.
• 11-18-2005
Quantum1024
I think the OP is talking about a program where the user thinks of a number and the AI tries to guese it, something like this:
Quote:

Welcome to the guessing game! Think of a number and I will guess it.
I guese 10
is it (h)igher or (l)ower?
h
I guese 20
...
• 11-18-2005
Darryl
pseudocode
Code:

```while(wrong) { guess = (min+max)/2 if (too_high) max = guess-1 else if (too_low) min = guess+1 else you guessed right }```
• 11-18-2005
IfYouSaySo
I was going to suggest a binary search, but Daryl beat me to it.