Smart way of finding a number with changing the range

Hello,

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.



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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace 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.
Last edited on
Topic archived. No new replies allowed.