could you help me in adding additional logic when the find number function randomly pick a number less than the guess number or greater than the guess number? I think the best way would be to change the range its looking at but i am not sure how to go about it.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
//this randomly picks a number to see if its the right guess number
int NumFinder(int &numi, int maxrange, int minimum)
{
return numi = (rand() % maxrange) + minimum;
}
void Numbergame(int num, int guessnum, int &guesscount, int maxrange, int minimum)
{
while (num != guessnum )
{
//cout<<"guess what number I randomly picked from 1 to 100 its = "<< guessnum <<endl;
NumFinder(num, maxrange, minimum);//here were picking a random number to see if it equals the guessnum
cout<<"My NumFinder function picked = "<< num << endl;
if (num < guessnum)
{
cout<<"you guessed to low"<<endl;
}
if (num > guessnum)
{
cout<<"you guessed to high"<<endl;
}
if (num == guessnum)
cout<<"you guessed right!"<<endl;
guesscount++;
}
}
int main()
{
srand(time(NULL));
int maxrange = 10000, minimum = 1;
int guessnum = (rand() % maxrange) + minimum,
num = 0, guesscount = 0;
Numbergame( num, guessnum, guesscount, maxrange, minimum);
cout<<"It took youre NumFinder this many tries = "<<guesscount<<endl;
return 0;
}
the smart way is to not pick randomly, but to cut it in half every time. (this is the binary search).
eg if you have 0-100 and the value is 22, ... pick 50. its less. pick 25, its less. pick 12, its more. pick (12+25)/2 = 18 its more. pick (18+25/2) = 21 and so on.
to randomly pick, the easy way is remainder thingy.
so if its between 12 and 25 from the above example...
value = randomvalue % (25-12+1) + 12; gives ([0-13]+12) = 12-25...
to smartly randomly pick, combine the above 2 approaches by making the random value closer to the average but still randomized by some amount.
eg
value = (x+y)/2 * (0.9+ pow(-1,randomvalue)*(randomvalue%15)/100) or some similar nonsense.