猜数字:计算机要猜多少次才能得到正确的数字
Guess the number: How many guesses for computer to get correct number?
我对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,你只使用二进制搜索算法,因为每次你的输入集都会减半。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- C++ 让计算机猜一个数字
- 为什么我的 64 位计算机不能在 C++ 中存储双精度数字 2^1024?
- 猜一个秘密数字(计算机vs计算机)——人工智能