Mastermind
This is a 3-digit variation of the mastermind puzzle. You are given a set of rules about the placement and number of digits and you attempt to find a solution that satisfies all rules.
Theory
Brute Force Search
With only 1000 possible combinations (000-999), we can check every candidate against all rules. For each guess, we count:
- Well-placed (green): correct digit in correct position
- Misplaced (yellow): correct digit in wrong position
- Incorrect (red): digit not in solution
def check_guess(guess, solution):
green = sum(g == s for g, s in zip(guess, solution))
yellow = sum(min(guess.count(d), solution.count(d)) for d in set(guess)) - green
return green, yellow
def solve(rules):
for code in range(1000):
candidate = [code // 100, (code // 10) % 10, code % 10]
if all(check_guess(r["digits"], candidate) == (r["green"], r["yellow"]) for r in rules):
yield candidateThe solver filters candidates that satisfy all constraints simultaneously.
Rules
5 rules1
2
5
7
2
8
4
2
3
3
7
1
4
5
6
9
5
6
0
7
Settings
Number of digits in the solution
Repeated digits allowed
Rules must match exactly (e.g. 1 well-placed means exactly 1, not at least 1)