I wrote a program where the computer guesses a random number.
To do this, I implemented a form of binary search. This correctly handles any edge-cases that I know of, including 0
and std::numeric_limits<int>::max()
. This doesn't handle negative numbers (since rand
will never return one) but that could easily be fixed.
The average amount of tries it takes to guess the number is around 29 or 30.
Here it is:
#include <functional>
#include <iostream>
#include <cstdlib>
#include <limits>
#include <ctime>
static int random_number;
int compare(int guess)
{
if(guess > random_number)
return 1;
if(guess < random_number)
return -1;
return 0;
}
struct guess_stats
{
int guesses = 0;
int number = 0;
};
guess_stats finder(std::function<int(int)> &&cmp)
{
int max = std::numeric_limits<int>::max();
int min = 0;
int guess = (min + max) / 2;
int cmp_result;
guess_stats results;
do
{
cmp_result = cmp(guess);
if(cmp_result < 0)
{
std::cout << "Greater than " << guess;
min = guess;
const int diff = max - guess;
guess += diff - (diff / 2);
}
else if(cmp_result > 0)
{
std::cout << "Less than " << guess;
max = guess;
const int diff = guess - min;
guess -= diff - (diff / 2);
}
std::cout << '\n';
results.guesses++;
} while(cmp_result);
results.number = guess;
return results;
}
int main(void)
{
std::srand(std::time(0));
random_number = std::rand();
guess_stats stats = finder(compare);
std::cout << "Number: " << stats.number << '\n'
<< "Guesses: " << stats.guesses << '\n';
return 0;
}
What I'm looking for:
- Although I don't expect there will be, are there any edge-cases I may not have seen?
- Are there any algorithmic changes that I could make to have less time-complexity? I don't think so (because this is only
O(log n)
as it is), but I may be surprised to find out. - Are there any better ways to generate random numbers? I used
srand
,time
, andrand
in this program, but those are old solutions. I imagine C++ has something much more up-to-date for generation of random numbers. - Any other general advice on what to improve would be appreciated.