c++ - 猜数字 : How many guesses for computer to get correct number?

标签 c++ math

我对 C++ 和一般编程还很陌生。我决定要制作一个“猜数字”游戏,但我想看看计算机平均需要猜多少次才能猜出 1 到 10,000,000 之间的数字。

我能想到的找到“ secret ”号码的最简单方法是 1. 将范围除以二(除数),这就是猜测。

一个。如果猜测大于“ secret ”数字,则猜测 1 成为范围的新最大值,然后我返回步骤 1。 b.如果猜测值低于“ secret ”数字,则猜测值+1 成为范围的新最小值,然后我返回步骤 1。

重复此过程直到找到数字。根据我的经验,计算机需要 22 次猜测才能猜出“ secret ”数字。

为了好玩,我想看看如果我改变除数会发生什么。对于 2 到 10 的除数范围内的 1,000,000 次迭代尝试猜测 1 到 10,000,000 之间的数字的结果,我实际上有点惊讶。

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 时,计算机平均能够使用更少的猜测来找到“ secret ”数字。

我的代码如下。

#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。

如果您的随机数非常小,这将偏向于较大的除数。

考虑使用 < random > 而不是在 C++11 中。像这样的东西:

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

关于c++ - 猜数字 : How many guesses for computer to get correct number?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26909167/

相关文章:

c++ - c++中读取函数的一个问题

algorithm - 求解递归 T(n) = 2T(n/2) + n^4

c++ - 多项式拟合力一次为零

c++ - C 或 C++ 中是否有 "inverted"trunc 函数?

math - Inkscape .91 带 latex

java - 如何取消忽略 SWIG 中模板化类的特定方法?

c++ - setw() 在我的代码上无法正常工作

c++ - Visual C++ 2010 原子类型支持?

c++ - 与 OpenMP、MPI 和 CUDA 链接时的 Autotools 问题

algorithm - 计算两个经纬度点之间的距离? (哈弗斯公式)