You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
Given the secret number and your friend’s guess, return the hint in the format xAyB
where x
is the number of bulls and y
is the number of cows.
Note:
xAyB
where x
is the number of bulls and y
is the number of cows.xAyB
.#include <string>
#include <vector>
#include <algorithm>
std::string getHint(std::string secret, std::string guess) {
int bulls = 0, cows = 0;
std::vector<int> secretFrequency(10, 0), guessFrequency(10, 0);
// First pass to count bulls and record frequencies
for (int i = 0; i < secret.size(); ++i) {
if (secret[i] == guess[i]) {
++bulls;
} else {
++secretFrequency[secret[i] - '0'];
++guessFrequency[guess[i] - '0'];
}
}
// Count cows
for (int i = 0; i < 10; ++i) {
cows += std::min(secretFrequency[i], guessFrequency[i]);
}
return std::to_string(bulls) + "A" + std::to_string(cows) + "B";
}
In the code:
secretFrequency
and guessFrequency
to count occurrences of digits that are not in the correct position.std::min(secretFrequency[i], guessFrequency[i])
gives us the number of cows for each digit.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?