#include #include using std::cout; using std::cin; using std::min; int answer[4] = { 0 }; int answer_counts[7] = { 0 }; // More obvious, less inspired algorithm void evaluate_guess( int guess[], int& black, int& white ) { bool used[4] = { false, false, false, false }; black = white = 0; // Compute the black answer for (int i=0; i < 4; ++i) if (guess[i] == answer[i]) { black++; used[i] = true; } // Compute the white answer exactly for (int i=0; i < 4; ++i) // step thru the guess slots for (int j=0; j < 4; ++j) { // step thru the answer slots // If this slot in answer has been previouly used, skip it if (used[j]) continue; if (guess[i] == answer[j]) { white++; used[j] = true; // Now that this guess slot has been "bound" to an answer slot, // don't try to match it to another answer slot break; } } } // More inspired, less complex algorithm void evaluate_guess( int guess[], int& black, int& white ) { int guess_counts[7] = { 0 }; black = white = 0; // Count the number of occurrences of each digit in the guess // answer_counts was computed in main() for (int i=0; i < 4; ++i) guess_counts[ guess[i] ]++; // Compute the black answer for (int i=0; i < 4; ++i) if (guess[i] == answer[i]) black++; // Over-compute the white answer for (int i=1; i < 7; ++i) white += min( guess_counts[i], answer_counts[i] ); // Remove the black answer from the white answer white = white - black; } void get_answer( int input[] ) { for (int i=0; i < 4; ++i) input[i] = answer[i]; } int main( void ) { srand( time( 0 ) ); for (int i=0; i < 4; ++i) answer[i] = rand() % 6 + 1; for (int i=0; i < 4; ++i) answer_counts[ answer[i] ]++; int guess[4], white, black=0; while (black != 4) { cout << "Input: "; cin >> guess[0] >> guess[1] >> guess[2] >> guess[3]; cout << " "; if (guess[0]) { evaluate_guess( guess, black, white ); cout << black << " " << white << '\n'; } else { get_answer( guess ); cout << guess[0] <<' '<< guess[1] <<' '<< guess[2] <<' '<< guess[3] << '\n'; } } } // Input: 0 0 0 0 // 3 4 5 4 // Input: 3 3 4 4 // 2 1 // Input: 5 5 6 6 // 0 1 // Input: 3 4 4 5 // 2 2 // Input: 4 3 4 5 // 0 4 // Input: 3 4 5 4 // 4 0 // Input: 1 1 2 2 // 0 0 // Input: 3 3 4 4 // 1 1 // Input: 3 4 5 5 // 1 1 // Input: 3 4 6 6 // 0 2 // Input: 6 3 5 3 // 2 2 // Input: 6 3 3 5 // 4 0 // Input: 5 5 6 6 // 2 0 // Input: 3 3 4 4 // 1 0 // Input: 5 5 4 2 // 1 0 // Input: 5 3 6 1 // 4 0