Bulls and cows is a variation of the popular game called 'Mastermind', On a sheet of paper, the players each write a 4-digit secret number. The digits must be all different. Then, in turn, the players try to guess their opponent's number who gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows"
One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how the last guess was scored. The next guess can be any number from the pruned list.
Either the program guess correctly or run out of numbers to guess, which indicates a problem with the scoring.
This is the implementation for n digits in C++, hunters (the list of all possible numbers that could be the answer) is a vector
of string
and cows it he function that counts the cows from two numbers:
for(int h=0; Hunters.size() > 1; h++){
askBullsCows(h);
string guess = Hunters.at(0);
for(int i=Hunters.size()-1; i >= 0; i--){
int pl = 0, fl = 0;
for (unsigned int ix = 0; ix < Hunters.size(); ix++){
if(Hunters[i].at(ix) == guess.at(ix)) pl++;
}
Cows(i, guess, fl);
if((pl != P.p) || (fl != P.f)){
Hunters.erase(cazadores.begin()+i);}
}
}
Now, hunters (the vector
) have more than 150.000 string
s and it's too expensive for erase one by one string
that couldn't be the answer.