开发者

Understanding algorithm for finding a random number

开发者 https://www.devze.com 2023-03-07 19:21 出处:网络
I\'m trying to find the best algorithm for finding a random number between 1-100 using the least number of steps. You can guess a number n using the function guess(n), and you will receive a boolean r

I'm trying to find the best algorithm for finding a random number between 1-100 using the least number of steps. You can guess a number n using the function guess(n), and you will receive a boolean r开发者_StackOverflowesponse true or false. The answer will always be less than the guess you entered into the function if the response is false; if the response is true, it needs to be larger or the guess itself.


The basic idea:

First guess(50). Depending on the answer, guess(25) or guess(75).


If you can tell whether your guess is greater or smaller than the random number, then Binary Search is your friend.

Else, if you can only tell if the numbers match, I would start alternating linear search from the median (50.5) i.e. from 50 to 1 and from 51 to 100 (50, 51, 49, 52...).

0

精彩评论

暂无评论...
验证码 换一张
取 消