【问题标题】:Implementing binary search guessing game [closed]实现二分搜索猜谜游戏
【发布时间】:2015-12-24 19:30:51
【问题描述】:

我正在尝试编写一个程序,让计算机尝试猜测用户选择的数字(1 - 100)。我已经写出了大部分程序,并且还制作了一个随机数生成器。我现在唯一需要的是一种基于用户输入的 HIGH 或 LOW 在我的程序中实现二进制搜索算法的方法。我已经阅读了一些关于二进制搜索算法的内容,但我不确定如何在我的程序中使用它。有人能指出我正确的方向吗?

第 34 行和第 42 行在应该有函数的地方有一个空白。这就是我想在我的程序中输入某种可以实现二进制搜索算法的方程的地方。

以下是我现在的代码:

#include <iostream>
#include <ctime>//A user stated that using this piece of code would make a true randomization process.
#include <cstdlib>
#include <windows.h>
using namespace std;

int main()
{
    int highLow;
    int yesNo;
    int ranNum;
    srand( time(0));


    ranNum = rand() % 100 + 1;

    cout << "Please think of a number between 1-100. I'm going to try to guess it.\n";
    _sleep(3000);

    cout << "I'm going to make a guess. Is it "<< ranNum <<" (1 for yes and 2 for no)?\n";
    cin >> yesNo;


    while (yesNo == 2)
        {
            cout << "Please tell me if my guess was higher or lower than your number\n";
            cout << "by inputting 3 for HIGHER and 4 for LOWER.\n";
            cin >> highLow;

            if (highLow == 3)
                {
                    cout << "Okay, so my guess was higher than your number. Let me try again.\n";
                    _sleep (1500);
                    cout << "Was your number " <<  <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
                //binary search algorithm in this line of code.
                    cin >> yesNo;
                }
            if (highLow == 4)
                {
                    cout << "Okay, so my guess was lower than your number. Let me try again.\n";
                    _sleep (1500);
                    cout << "Was your number " <<  <<"? If yes, input 1. If not, input 2.\n";// I would like to find a way to implement the
                //binary search algorithm in this line of code.
                    cin >> yesNo;
                }
        }
        if (yesNo == 1)
        {
            cout << "My guess was correct!\n";
        }
}

【问题讨论】:

  • 你有二分查找功能吗?如果没有,您应该做的第一件事是创建一个并在硬编码输入上对其进行测试。一旦测试正确,您就可以将其应用到更大的程序中。
  • 欢迎来到 StackOverflow。虽然您的问题无疑很有趣,但 SO 不是代码编写服务。例如,您可以询问现有但有缺陷​​的二分搜索算法、各种损坏的 API,但不能询问容易引起争论或长时间讨论的问题。 SO 也不是博客。

标签: c++ algorithm random binary-search


【解决方案1】:

保留两个整数bottomtoploop invariant 是用户的号码在 [bottom;顶]。

现在我们要尽量减少猜测次数。为此,我们希望尽可能多地从 [底部; top] 一组数字(如果我们猜错了)。

为了尽可能多地扔掉,我们总是可以猜测floor((bottom + top) / 2)

为了实现这一点,我们可以根据我们的新信息调整bottomtop。如果它太高,我们将top 设置为guess - 1。如果太低,我们将bottom 设置为guess + 1

在最坏的情况下使用此策略,您只需猜测floor(log2(100)) = 6 次。有 1000 个数字可供选择 - 9 次猜测就足够了。

假设搜索的数字是 2。所以,我们猜测:50(高)、25(高)、12(高)、6(高)、3(高)、1(低)。我们不会猜测/询问用户 2,因为我们已经 100% 确定它是 2。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多