计算机猜测你想到的数字总是需要猜测的数量

时间:2016-09-27 13:42:01

标签: java logic

好的,所以问题不一定是实际代码,因为它有效,而是逻辑。问题是计算机需要多少猜测才能得到你想到的数字?在1-100之间,只要在1-100之间,无论它是什么,它总是会在7次尝试中猜出你的数字。接下来的问题是1-50,我发现只需要5次尝试就可以猜出你的号码。

import java.util.Scanner;

public class ThinkofaNumber {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Guess a number between 1 and 100");
    System.out.println();
    int input = 0;
    //guess is equal to half the highest number
    int guess = 50;
    //low is equal to the lowest
    int low = 1;
    //high is equal to the highest number
    int high = 101;
    int tries = 1;

    while (input != 2) {
        System.out.println("Is your number " + guess + "?");
        System.out.println("1: No, my number is lower");
        System.out.println("2: Yes, that is my number");
        System.out.println("3: No, my number is higher");
        System.out.println();

        input = in.nextInt();

        if (input == 1) {
            high = guess;
            guess = low + (guess - low) / 2;
            tries++;

        } else if(input == 3) {
            low = guess;
            guess = guess + (high - guess) / 2;
            tries++;
        }

    }


    System.out.println("Your number is " + guess + "!");

    if (tries  == 1) {

        System.out.println("It took 1 try to guess " + guess);

    } else {


        System.out.println("It took " + tries + " guesses to get " + guess);
    }

}
}

问题是接下来的问题是,如果数字在1到400之间,您认为有多少猜测会是多少?如果介于1到800之间怎么办?在1到1600之间?我认为它试图让我找到一个模式或算法,但我没有看到它。你们觉得怎么样?

3 个答案:

答案 0 :(得分:2)

您正在谈论的算法是二进制搜索算法。 https://en.wikipedia.org/wiki/Binary_search_algorithm

答案 1 :(得分:2)

这是一种二进制搜索算法,正如Wojciech所说。数字7来自以下log2(100)= 6.6 round to 7。

所以你可以做log base 2来找到猜测次数

答案 2 :(得分:1)

只是从@ Wael的回答中提供更多细分。

有关二元搜索算法的更多讨论可以找到here,而this answer我们知道 2 N + 1 -1 给了我们任意数量猜测的范围(1..X N

所以我们可以通过说:

来进一步解决这个问题

2 N + 1 -1 = 800

2 N + 1 = 801

log 2 801 = N + 1

log 2 801 -1 = N

即。 8.646 = N,N = 9

因此,猜测1到800之间的数字最多需要9次猜测。

我还应该指出 2 N + 1 -1 最坏情况,所以当试图找到数量时对于给定输入的猜测,它将根据输入而变化。