clueless coding // TODO: be smarter

LeetCode 299. Bulls and Cows: C++ Solution



Problem Statement


You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows.

Function Signature (C++):
  string getHint(string secret, string guess)

Inputs:
Secret number:  "1807"
Guess: "7810"

Outputs:
1 bull, 3 cows

The bull is at 8.
The cows are 1, 0, 7.

Inputs:
Secret number:  "1123"
Guess: "0111"

Outputs:
1 bull, 1 cow
The bull is the second 1.
There are two cows (both 1s in the secret), but one has already been 'used' as a bull.
Therefore, there's only one cow.



TL;DR Code Solution


string getHint(string secret, string guess) {

    int bulls = 0;
    int cows = 0;

    unordered_map<char, int> map;
    for (int i = 0; i < guess.length(); i++) {
        if (guess[i] == secret[i]) {
            bulls++;
        }
        else {
            map[guess[i]]++;
        }
    }

    for (int i = 0; i < secret.length(); i++) {
        if (guess[i] == secret[i]) {
            continue;
        }
        if (map[secret[i]] > 0) {
            cows++;
            map[secret[i]]--;
        }
    }

    return to_string(bulls) + "A" + to_string(cows) + "B";

}