1. ## 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;
}```

2. Have the AI guese by generating random numbers. After each guese ajust the min or max random number values.

3. So you want to make a game that's impossible to win?

4. 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.

5. 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:
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
...

6. 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
}```

7. I was going to suggest a binary search, but Daryl beat me to it.

Popular pages Recent additions