The Game of Master Mind is played as follows. The computer chooses a code consisting of four colors from {R, Y, G, B}. A player makes a guess (also four colors). For each guess the player is told:
hits (correct color in correct position), and
pseudo-hits (correct color in wrong position).
Example:
1
2
3
4
Solution: RGGB
Guess: YRGB
Hits: 2(positions 3 and 4)Pseudo-hits:1(color R exists but in wrong position)
Return the number of hits and pseudo-hits for a given guess and solution.
Note: LeetCode has a very similar problem titled “Bulls and Cows” (LeetCode 299) which asks for counts of bulls and cows — equivalent to hits and pseudo-hits.
Count exact matches (hits) in one pass. For non-matching positions, count remaining colors in the solution and then match them against the guess to compute pseudo-hits.
classSolution {
public: pair<int,int> masterMind(const string& guess, const string& solution) {
auto idx = [](char c){ return c =='R'?0: c =='Y'?1: c =='G'?2:3; };
int hits =0, pseudo =0;
int cnt[4] = {0,0,0,0};
for (size_t i =0; i < guess.size(); ++i) {
if (guess[i] == solution[i]) ++hits;
else++cnt[idx(solution[i])];
}
for (size_t i =0; i < guess.size(); ++i) {
if (guess[i] == solution[i]) continue;
int j = idx(guess[i]);
if (cnt[j] >0) { --cnt[j]; ++pseudo; }
}
return {hits, pseudo};
}
};
For very small fixed alphabets (here 4 colors) you can pack presence information into small integers and test membership with bit operations; however frequency counts are clearer and safer when duplicates exist.