Skip to content

Commit

Permalink
bulls-and-cows (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
aolenevme authored Jan 11, 2023
1 parent 68f8c69 commit b78bf7f
Showing 1 changed file with 92 additions and 0 deletions.
92 changes: 92 additions & 0 deletions string/bulls-and-cows.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
299. Bulls and Cows
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:
The number of "bulls", which are digits in the guess that are in the correct position.
The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.
Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.
The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1807"
|
"7810"
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: Bulls are connected with a '|' and cows are underlined:
"1123" "1123"
| or |
"0111" "0111"
Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.
Constraints:
1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret and guess consist of digits only.
*/

/**
* @param {string} secret
* @param {string} guess
* @return {string}
*/
var getHint = function (secret, guess) {
const map = {};

for (let i = 0; i < secret.length; i++) {
const char = secret[i];

if (char in map) {
map[char][i] = i;
} else {
map[char] = { [i]: i };
}
}

const checkedIndicies = {};
let bulls = 0;
let cows = 0;
for (let i = 0; i < guess.length; i++) {
const char = guess[i];

if (char in map && i in map[char]) {
bulls++;
checkedIndicies[i] = i;

delete map[char][i];

const isEmpty = Object.keys(map[char]).length === 0;
if (isEmpty) {
delete map[char];
}
}
}

for (let i = 0; i < guess.length; i++) {
const char = guess[i];

if (!(i in checkedIndicies) && char in map) {
cows++;

const firstKey = Object.keys(map[char]).at(0);

delete map[char][firstKey];

const isEmpty = Object.keys(map[char]).length === 0;
if (isEmpty) {
delete map[char];
}
}
}

return `${bulls}A${cows}B`;
};

0 comments on commit b78bf7f

Please sign in to comment.