Mastermind is a two-player game in which the first player attempts to guess the secret code of the second. In this version, the code may be any six-digit number with all distinct digits.
Each turn the first player guesses some number, and the second player responds by saying how many digits in this number correctly matched their location in the secret code. For example, if the secret code were 123456, then a guess of 175286 would score two, since 1 and 6 were correctly placed.
Write an algorithm which, given a sequence of guesses and their scores, determines whether there exists some secret code that could have produced them.
To solve this problem, we need to check if there exists any six-digit number with distinct digits that matches all the given guesses with the specified number of correct positions. This is effectively a constraint satisfaction problem, where we systematically check each potential secret code to see if it satisfies all the given conditions.
Here are the steps we can take:
Generate All Possible Secret Codes:
As the secret code is a six-digit number with all distinct digits, we can generate all permutations of the digits 0 through 9, selecting only those with six digits.
Validate the Secret Code:
For each generated secret code, compare it with each guess to check if the number of correctly positioned digits matches the given score.
Output the Result:
If we find at least one secret code that satisfies all conditions, return True. Otherwise, return False.
from itertools import permutations
defis_possible_secret_code(guesses):
for perm in permutations("0123456789", 6):
secret_code ="".join(perm)
# Check if this secret code matches all the given guesses and scoresif all(
score == sum(sc == g for sc, g in zip(secret_code, str(guess)))
for guess, score in guesses.items()
):
returnTruereturnFalse# Example usage:guesses1 = {175286: 2, 293416: 3, 654321: 0}
guesses2 = {123456: 4, 345678: 4, 567890: 4}
print(is_possible_secret_code(guesses1)) # Output: Trueprint(is_possible_secret_code(guesses2)) # Output: False