jeudi 24 décembre 2015

C++: Implementing Binary Search in RNG Guessing Game

I'm trying to write a program where the computer attempts to guess a number that the user selects ( 1 - 100 ). I have most of the program written out, and have also made a random number generator. The only thing I need now is a way to implement the binary search algorithm into my program based on the user's inputs of HIGH or LOW. I've read some about the binary search algorithm, but I'm not sure how to use it in my program. Could someone point me in the right direction?

Lines 34 and 42 have a blank where there should be a function. That's where I would like to input some sort of equation that would implement the binary search algorithm into my program.

Below is my code as of now:

#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";
        }
}




Aucun commentaire:

Enregistrer un commentaire