猜数字:计算机要猜多少次才能得到正确的数字

Guess the number: How many guesses for computer to get correct number?

本文关键字:数字 计算机 多少次      更新时间:2023-10-16

我对C++和编程很陌生。我决定做一个"猜数字"游戏,但我想看看电脑平均需要猜多少次才能猜出一个介于1到10000000之间的数字。

我能想到的找到"秘密"号码的最简单方法是1.取这个范围,除以二(除数),这就是猜测。

a。如果猜测值大于"秘密"数,则guess-1将成为该范围的新最大值,然后返回步骤1。b.如果猜测低于"秘密"数,则猜测+1成为范围的新最小值,我返回步骤1。

重复此操作,直到找到编号为止。根据我的经验,计算机需要22次猜测才能猜出"秘密"数字。

为了好玩,我想看看如果我改变除数会发生什么。事实上,我对1000000次迭代的结果感到有点惊讶,这些迭代试图猜测从2到10的除数范围内1到10000000之间的数字。

Average with divisor 2 is 22.3195
Average with divisor 3 is 20.5549
Average with divisor 4 is 20.9087
Average with divisor 5 is 22.0998
Average with divisor 6 is 23.1571
Average with divisor 7 is 25.5232
Average with divisor 8 is 25.927
Average with divisor 9 is 27.1941
Average with divisor 10 is 28.0839

我很想知道为什么当使用除数3、4和5时,计算机平均能够用更少的猜测来找到"秘密"数字。

我的代码在下面。

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <vector>
using namespace std;
int half_search(int a, int b, int n, int m)
{
    int aMax = b;
    int aMin = a;
    int divisor = m;
    int result;
    static int counter = 0;
    double guess = ((static_cast<double>(b) - a) / divisor) + aMin;
    if(guess - static_cast<int>(guess) >= 0.5)
        guess = ceil(guess);
    if(guess < n)
    {
        aMin = guess + 1;
        counter++;
        half_search(aMin, aMax, n, divisor);
    }
    else if(guess > n)
    {
        aMax = guess - 1;
        counter++;
        half_search(aMin, aMax, n, divisor);
    }
    else
    {
        counter++;
        result = counter;
        counter = 0;
        return result;
    }
}
int main()
{
    const int MIN = 1;
    const int MAX = 10000000;
    int k = 0;
    int j = 2; //represents lowest divisor
    int l = 10; //represent highest divisor
    int iterations = 100000;
    double stepSum = 0;
    vector<int> myVector(iterations);
    srand(1);
    while(j <=10)
    {
        while(k < iterations)
        {
            int n = rand() % MAX + 1;
            myVector[k] = half_search(MIN, MAX, n, j);
            stepSum += myVector[k];
            k++;
        }
        cout << "Average with divisor " << j << " is " << stepSum / iterations << endl;
        j++;
        k = 0;
        stepSum = 0;
    }
    return 0;
}

在某些编译器(如Visual Studio 2013)上,int n = rand() % MAX + 1;只提供1到32768之间的数字,因为RAND_MAX可能低至32767。

如果你的随机数很小,这将偏向于更大的除数。

考虑使用<随机>。类似于:

std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<> dist(1, MAX);
//...
int n = dist(mt);

除以2总是更快,并提高性能,因为这对CPU来说更容易,占用的时钟周期更少。这就是所谓的二进制搜索。通过使用其他除数,你可以减少"猜测",直到它不得不多次询问"秘密"比"猜测"大或低的地方。

我也看到了除数为2的最佳结果。这种情况也应该是这样的,因为通过使用除数2,你只使用二进制搜索算法,因为每次你的输入集都会减半。