It's a bulls and cows games. Many of you may have heard of it, if not, here is an example:
A two-player number-guessing game called “Bulls and Cows”, to be
played between a the computer and a person.1 The computer thinks of a secret number sequence, consisting of four distinct numbers, each in the range {0, 1, . . . , 9}. The human opponent has to determine these four numbers, in their proper sequence, by making repeated guesses. A guess of a number in its proper slot is called a “bull”, whereas a guess in a number that’s not in its proper slot is called a “cow”. For example, if the secret number sequence is 3, 1, 4, 5 and the human opponent guesses 3, 2, 5, 4, then the computer would output
Bulls: 1, Cows: 2.
Here's my code:
#include <bjarne/std_lib_facilities.h>
void offer_help()
{
cout << "The program will generate a secret number sequence, consisting of four distinct numbers, each in the range 0 to 9. You have to determine these four numbers, in their proper sequences by making repeated guesses. A guess of a number in its proper slot is called a 'bull', whereas a guess in a number that is not in its proper slot is called a 'cow'. You can input negative numbers to give up.\n";
}
int main(){
cout << "Need help (0/1)? ";
int help;
cin >> help;
if (help==1){
offer_help();
}
if (help!=0 && help!=1) error("Please enter 0 for no or 1 for yes.\n");
for (;
{
vector<int> answer ={1, 2, 3, 4};
vector<int> guess;
int bulls=0;
int cows=0;
for (int times=0; times<4; times++){
int g;
cin>>g;
guess.push_back(g);}
if (guess[0]<0 || guess[1] <0 || guess[2] <0 || guess[3] <0) error("Negative number detected, byebye.\n");
if (guess[0]>9 || guess[1]>9 || guess[2]>9 || guess[3]>9 || (!cin)) error("Please enter intergers from 0 to 9.\n");
if (guess[0]==guess[1] || guess[0]==guess[2] || guess[0]==guess[3] || guess[1]==guess[2] || guess[1]==guess[3] || guess[2]==guess[3]) error("Please enter four different numbers.\n");
if (guess[0]==answer[0])
bulls++;
else if (guess[0] == answer[1] || answer[2] || answer[3])
cows++;
if (guess[1]==answer[1])
bulls++;
else if (guess[1] == answer[0] || answer[2] || answer[3])
cows++;
if (guess[2]==answer[2])
bulls++;
else if (guess[2] == answer[0] || answer[1] || answer[3])
cows++;
if (guess[3]==answer[3])
bulls++;
else if (guess[3] == answer[0] || answer[1] || answer[2])
cows++;
if (bulls<4)
cout << "There are " <<bulls<< " bulls, " <<cows<< " cows. Try again.\n";
else if (bulls==4)
cout << "Congratulations! Let's do it one more time! (Input negative numbers when you want to quit.\n";
}
}
Here's my 1st problem(I might have more after I finish this step):
How can I generate 4 random numbers? I'm now using four fixed numbers so that I can do the rest of the code(this exercise is based on Stroustrup's PPP chapter 1-5, which doesnt seem to have ran() or whatever.)