-3

I am trying to create a simple game where the user inputs a number, and the computer tries to guess it. The program randomly generates a number between 1 & 100. Whenever the user says a number is too high it stores that value, and every value above that, in an array and vice versa for too low. Then I want the program to generate another random number, but if the number it generates is within the array of wrong numbers, it tries again. But I have absolutely no idea how to check if the number is present in the array. Is this possible?

Starfruit
  • 409
  • 1
  • 4
  • 9
  • 4
    Possible duplicate of [Check if element found in array c++](http://stackoverflow.com/questions/19215027/check-if-element-found-in-array-c) – Tamás Sengel Apr 09 '17 at 21:36

2 Answers2

1

Yes, this is possible. You will want to use the std::find() algorithm, the reference page for which can be found Here.

It is called as std::find(std::begin(array), std::end(array), someObject); and returns an iterator to the first element in the range [first,last) that compares equal to someObject. If no such element is found, the function returns last element i.e. end of range.

In building your random number game I would consider whether, checking if the computers guess is out of range and then guessing again if so, is the best way to approach the problem (because it's not the best way).

Also before asking a question please try to find similar questions such as This, or This before asking a new question in order to prevent stackoverflow from becoming too cluttered

Community
  • 1
  • 1
Ace.C
  • 1,201
  • 12
  • 22
1

For that game you don't need an array. Look at the following program:

#include <iostream>

constexpr long long average (long long a, long long b)
{
    return (a+b)>>1;
}

int main()
{
    char ans;
    long long start, end;
    std::cin >> start >> end;
    do
    {
        auto n=average(start,end);
        std::cout << n << std::endl;
        std::cin >> ans;
        if(ans=='<') end=n-1;
        else if(ans=='>') start=n+1;
    }
    while(ans!='=');
}

Think of a number in the range [start, end] and the program will guess it. It uses binary search algorithm so it will need approximately log2(end-start+1) tries in the worst case.

Lassie
  • 853
  • 8
  • 18