The most efficient way to guess a number within a range is to divide the subset of possible answers
in half each iteration. This type of technique can be seen in many places in computer science algorithms, such as sorting or mathematical transforms (FFT), and is known as "divide and conquer"
https://en.wikipedia.org/wiki/Divide_and_conquer_algorithm
I'll give an example.
Say the number to guess is within the range 1-100, as you have it, and the number generated is 65.
On the first iteration, all options are equally possible. So what you should do is guess 50, because that will divide your set in half, which is,
on average, the best way to remove the most possibilities at once.
The guess (50) was lower than the actual number (65), so the new low is 51, and your new range is [51, 100].
Now, your next guess should be the new halfway point: (51+100)/2 rounded, or 76.
76 is greater than 65, so the new high is 75.
Your range is now [51, 75].
Rinse and repeat... the maximum amount of iterations you should have to perform is log
2(100) ("log base 2 of 100" or ~6.64), rounded up to 7 iterations. Why log
2(100) though? Because that's the number of halvings it takes to get from 100 to 1: 50, 25, 12.5, 6.25, 3.125, 1.5625, 0.78125.
It can also be easier to think of it in binary.
01111111 127 = 27-1
00111111 63 = 26-1
00011111 31 = 25-1
00001111 15 = 24-1
00000111 7 = 23-1
00000011 3 = 22-1
00000001 1 = 21-1 |
tl;dr -- always guess the half-way point between the current range.