-
Notifications
You must be signed in to change notification settings - Fork 247
Cows and Bulls
LeWiz24 edited this page Aug 13, 2024
·
2 revisions
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Q
- What is the desired outcome?
- To return the hint for a guess in the format
"xAyB"
, wherex
is the number of bulls andy
is the number of cows.
- To return the hint for a guess in the format
- What input is provided?
- Two strings,
secret
andguess
.
- Two strings,
- What is the desired outcome?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Count the bulls in the first pass and the cows in the second pass using Counter
.
1) Initialize `bulls` and `cows` to 0.
2) Initialize two `Counter` objects `secret_count` and `guess_count`.
3) First pass: Count the bulls and populate the `Counter` objects for non-bull characters.
4) Second pass: Count the cows by finding the minimum count of matching characters in `secret_count` and `guess_count`.
5) Return the result as a string in the format `"xAyB"`.
- Miscounting cows by not properly excluding bull positions.
from collections import Counter
def get_hint(secret, guess):
bulls = 0
cows = 0
secret_count = Counter()
guess_count = Counter()
# First pass to count bulls
for i in range(len(secret)):
if secret[i] == guess[i]:
bulls += 1
else:
secret_count[secret[i]] += 1
guess_count[guess[i]] += 1
# Second pass to count cows
for char in guess_count:
if char in secret_count:
cows += min(secret_count[char], guess_count[char])
return f"{bulls}A{cows}B"