Http://www.programmerinterview.com/index.php/puzzles/minimum-guesses-1-100/
Given the numbers 1 to +, what's the minimum number of guesses needed to find a specific number if you are Given the H int ' higher ' or ' lower ' for each guess?
This could be considered a trick question, since it's deceptively easy. Read the question carefully and you'll note that the question asks for the ' minimum ' number of guesses. Think about It–someone can guess the right question on their first try right?
So, the answer here would is ' 1 ', since it would take only one correct guess to find a specific number.
Finding the maximum number of guesses
But, what if we wanted to find the maximum number of guesses?
Well, think on this one. What if the number so you had to guess was ' 1 ' and you start guessing from 1,000? Then, if the person who knows the number keeps saying lower and then you would guess 999,998,997 ... 6,5,4,3,2, and finally until you get to 1.
The maximum number of guesses
This means, the maximum number of guesses is 999.
But, you must is thinking that's a stupid answer–because no one would take the approach to guessing unless they were re Ally foolish.
Using Binary Search to find a number from 1 to 1,000
The approach most programmers would take was by starting your guess in the middle of the set of numbers, and then Continuin G to divide the set of numbers in half with each guess. This approach to guessing (or "searching" for the number) are known as a binary search to most software engineers, And it is also known as a half-interval search. Let's go through an example of what the binary search would work so this you can further understand the approach to solving This problem.
An example of using the binary search
So, let's say the number were trying to guess is a ' 1 '. Then, you would start from the middle of 1,000–which is 500. The person giving your hints would keep saying lower–and you would end up with something like this sequence of numbers to Represent your guesses:
<pre= "Code" >500, 250, 125, 63, 32, 16, 8, 4, 2, 1
Counting the number of guesses above would give you, which are our answer to the maximum number of guesses to find a num ber between 1 and 1000. In a binary search, if you take the log base 2 of the number of numbers, which would also give you the Maximum number of guesses to find the correct number. So, if we take the log base 2 of the would give us 9.965. Since you can ' t possibly has a fraction of a guess, the result of the log base 2 of the should be rounded up to a whole numb Er, which is ten, and the answer.
Hiring? Job hunting? Post a job or your RESUME on our job BOARD >>
Subscribe to our newsletter for more free interview questions.
Follow @programmerintvw
Given the numbers 1 to +, what is the minimum number?