Click here to Skip to main content
15,913,709 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello everyone, I recently had some problems writing a code job about quick guessing numbers. The program is like this, by a user randomly wrote a four-digit (but the computer does not know how much), and then the computer to the user to ask questions to determine the number, specifically what content is not limited. But the user's question on the computer can only answer "yes" or "no". But the number of computer questions as little as possible. So, this question is different from "bulls and cows".But I need about 14 times to determine this number, and I can not find a solution with fewer questions, please help me, be grateful.

What I have tried:

In order to solve this problem, I try to use binary search method to write a piece of code. The specific description is, from the first to the fourth bit by bit to determine the corresponding number, each number in 0-9 using binary search method to determine, so an average of 14 times to determine the four digits.
Posted
Updated 29-May-17 12:20pm

You can do it in 13 steps for 4 digits, and the question is the same each time: Is it less than half the current value?
I.e.
Initial range: 0000 -> 9999
Is it less than 5000?
If yes, the range becomes 0000 - 4999. Next guess is "less than 2500?"
If no, the range becomes 5000 - 9999. Next guess is "less than 7500?"
Repeat, and in 13 steps you will have a single value.
 
Share this answer
 
Comments
CPallini 30-May-17 4:58am    
5.
Quote:
But I need about 14 times to determine this number, and I can not find a solution with fewer questions

Because there is no faster solution.
Dichotomy is the fastest way to solve your problem.
Your have 10000 possible numbers, and powers of 2 are 2^13= 8192 and 2^14= 16384.
This is where your 14 comes from.
 
Share this answer
 
Comments
CPallini 30-May-17 4:58am    
5.
Patrice T 30-May-17 6:01am    
Thank you again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900