Mastermind
Do you remember playing board games as a kid? I couldn't stop: Mastermind, Stratego, Chinese checkers, chess, Tripoley, cribbage, Pandemic, and Settlers of Catan. These days I'm just as hooked on the math underneath them, like what each move really tells you and how to find the one that's mathematically best. Mastermind is the perfect place to start, a deduction game small enough to solve completely.
The computer picks a secret code of four colored pegs, and you get ten guesses. Start on Easy, where every slot gets its own marker. When you're ready, switch to Hard for the classic rules, then read on to see why five guesses are always enough.
Let the solver crack your code
Set a secret (tap a peg to cycle its color), pick a strategy, and watch how each guess shrinks the set of possible codes.
| # | Guess | Reply | Possible before | After | Bits gained |
|---|
The math of winning in the fewest guesses
Mastermind is a search problem. Every guess is a question, and every reply rules out a set of codes. Playing well comes down to one idea: ask the question whose answer you can predict least.
- The search space
- How replies are scored
- Consistency: what's still possible
- Choosing the first guess
- Four ways to score a guess
- How the strategies compare
- Worked example
- Why five, not four?
- Playing it in your head
- References
1 · The search space
With 6 colors in 4 positions and repeats allowed, there are
"Bits" here are Shannon's measure of information[7]: each bit halves the number of possibilities.
Think of each guess as buying information. You win when the uncertainty reaches zero bits, meaning exactly one code is left, and you then guess that code.
2 · How replies are scored
For a guess g and secret s, the reply is a pair: exact pegs (traditionally black) and color-only pegs (traditionally white).
w(g, s) = Σcolors c min( nc(g), nc(s) ) − b(g, s)
Here nc(x) counts how many times color c appears in x. The min term counts every color match regardless of position, and subtracting b removes the ones already counted as exact. Note that b + w depends only on which colors are in the code, not on their order. That makes it the first lever for human players.
Since b + w ≤ 4, there are 15 pairs on paper. But 3 exact, 1 color-only is impossible (if three pegs are exact and the fourth color appears in the code, it has nowhere else to go), so there are exactly 14 possible replies.
3 · Consistency: what's still possible
The core operation is filtering. After guessing gk and hearing reply rk, keep only the codes that would have produced the same reply:
Any guess therefore partitions the remaining set into at most 14 buckets, one per reply, and the reply tells you which bucket you're in. A good guess makes every bucket small. A bad guess leaves one huge bucket that you'll probably land in.
4 · Choosing the first guess
Up to relabeling colors and positions, there are only five kinds of opener. Here is how each splits all 1,296 codes:
| Opener | Pattern | Worst bucket | Expected bucket | Entropy (bits) | Replies possible |
|---|---|---|---|---|---|
| 1111 | AAAA | 625 | 512.0 | 1.50 | 5 |
| 1112 | AAAB | 317 | 235.9 | 2.69 | 11 |
| 1122 | AABB | 256 ★ | 204.5 | 2.89 | 13 |
| 1123 | AABC | 276 | 185.3 ★ | 3.04 | 14 ★ |
| 1234 | ABCD | 312 | 188.2 | 3.06 ★ | 14 ★ |
"Expected bucket" is the size of the set you should expect to land in: Σ|Pr|² / |S|. Bigger buckets are more likely to be the one you land in, which is why the sizes are squared. No single opener wins on every measure. 1122 has the smallest worst case, 1123 the smallest expected remainder, and 1234 the most information. 1111 is a trap: 48% of the time it tells you only "no 1s".
5 · Four ways to score a guess
Write Pr(g) for the bucket of remaining codes that would answer guess g with reply r. Each classic strategy picks the g that optimizes one statistic of those buckets:
Expected size (Irving, 1979)[2]: minimize Σr |Pr(g)|² / |S|
Entropy (Neuwirth, 1982)[3]: maximize H(g) = −Σr pr log₂ pr, pr = |Pr(g)| / |S|
Most parts (Kooi, 2005)[5]: maximize #{ r : Pr(g) ≠ ∅ }
Two details matter in practice:
- Search all 1,296 guesses, not just the possible ones. Sometimes the best question is a code that can't be the answer: you give up a small chance of winning now for a much better split. The solver above does this, and the hint button tells you when it happens.
- Break ties toward possible codes. If two guesses split equally well, prefer the one that might win outright.
The same principle (choose the query whose answer most reduces uncertainty) underlies active learning, adaptive experiment design, and how a good AI agent decides which clarifying question to ask. Mastermind is a tidy place to build intuition for it.
6 · How the strategies compare
I computed every strategy below by playing it against all 1,296 secrets. The optimal row is from exhaustive search in the literature.
| Strategy | Opener | Avg guesses | Worst case |
|---|---|---|---|
| Always guess the first possible code (in order) | 1111 | 5.765 | 9 |
| Guess a random possible code | random | ≈ 4.66 | 7 |
| Minimax (Knuth) | 1122 | 4.476 | 5 ★ |
| Max entropy (Neuwirth) | 1234 | 4.415 | 6 |
| Expected size (Irving) | 1123 | 4.395 | 6 |
| Most parts (Kooi) | 1123 | 4.373 | 6 |
| Optimal average (Koyama & Lai, 1993)[4] | 1123 | 4.340 ★ | 6 |
Three takeaways:
- Any consistent play is decent. Just never guessing a code you've already ruled out gets you under 5 on average. That's the biggest single improvement over casual play.
- Greedy isn't optimal. Each heuristic looks only one move ahead. Entropy starting with its own favorite opener (1234) averages 4.415, but starting with 1123 the same rule averages 4.383. The best first question depends on what you can do with the answers later.
- Worst case and average case pull apart. Only minimax guarantees five guesses. The strategies with better averages occasionally need six.
Why Easy mode is easy: per-slot markers allow 77 distinct replies instead of 14, so each guess carries far more information. Minimax then needs only 3.30 guesses on average and never more than 4. Everything in this guide applies to both modes, but the classic (Hard) rules are where strategy really pays off.
7 · Worked example
Secret 4513, solved with minimax (open the solver above and set this code to replay it):
| # | Guess | Reply | Before | After | Bits |
|---|---|---|---|---|---|
| 1 | 1122 | 0 exact, 1 color | 1,296 | 256 | 2.34 |
| 2 | 2344 | 0 exact, 2 color | 256 | 41 | 2.64 |
| 3 | 3235 | 0 exact, 2 color | 41 | 2 | 4.36 |
| 4 | 4513 | 4 exact | 2 | ✓ | 1.00 |
Read it as a story. Guess 1 says the code has exactly one peg that is a 1 or a 2, and it's in the wrong half. Guess 2 finds two color matches among 2, 3 and 4, none of them in the guessed spots. Guess 3 is the clever one: it brings in 5 and reuses 3 in new positions, and 41 possibilities collapse to just 2 (4.36 bits from one reply, more than the best possible opener). After that, it's a coin flip the solver wins.
8 · Why five, not four?
A counting argument gives a floor. With 14 possible replies, two guesses can sort the codes into at most 14² = 196 groups. That's far fewer than 1,296, so you can never be certain of the code on your third guess. Three guesses allow 14³ = 2,744 groups, which on paper is enough to win on the fourth.
But real partitions are lopsided. Even the best opener produces only 13 or 14 buckets, the largest holding 256 codes, and no follow-up splits that bucket finely enough. Knuth showed that five guesses always suffice[1], and exhaustive search confirms that no strategy can guarantee four. The optimal-average strategy, at 4.340[4], has to accept a sixth guess for one code.
The same questions scale up. Chvátal[6] analyzed Mastermind with arbitrary numbers of colors and positions and bounded how the number of guesses must grow with board size, which helped turn a parlor game into a topic in combinatorics and complexity theory.
9 · Playing it in your head
You can't run minimax over 1,296 codes at the table, but you can approximate it:
- Open with 1122, then 3344. Each reply's
b + wtells you how many pegs come from that pair of colors. The count for {5, 6} is 4 minus the other two. Two guesses give you a color budget. - Settle which colors, then where. Once you know the colors, at most 4! = 24 orderings remain, and fewer if a color repeats. That's small enough to reason about directly.
- Use a dead color as a blank. When you know a color is absent, fill spots with it to test positions one at a time. Its pegs can't score, so the reply isolates the pegs you're testing.
- Only guess possible codes when few remain. With many possibilities, a guess that can't win but splits well is better. With three or fewer, always guess one that could win.
- Audit yourself. Turn on Show analysis while you play. Any guess that earns under about 1 bit was a wasted turn. Find out why.
References
- D. E. Knuth. "The computer as Master Mind." Journal of Recreational Mathematics 9(1):1–6, 1976–77.
- R. W. Irving. "Towards an optimum Mastermind strategy." Journal of Recreational Mathematics 11(2):81–87, 1978–79.
- E. Neuwirth. "Some strategies for Mastermind." Zeitschrift für Operations Research 26:B257–B278, 1982. doi:10.1007/BF01917147
- K. Koyama and T. W. Lai. "An optimal Mastermind strategy." Journal of Recreational Mathematics 25(4):251–256, 1993.
- B. Kooi. "Yet another Mastermind strategy." ICGA Journal 28(1):13–20, 2005. doi:10.3233/ICG-2005-28105
- V. Chvátal. "Mastermind." Combinatorica 3(3–4):325–329, 1983. doi:10.1007/BF02579188
- C. E. Shannon. "A mathematical theory of communication." Bell System Technical Journal 27(3):379–423, 1948. doi:10.1002/j.1538-7305.1948.tb01338.x
All averages and worst cases in the tables above were recomputed for this page by playing each strategy against all 1,296 secrets; they agree with the published values.
Mastermind is a trademark of its respective owner. This is an independent, non-commercial implementation for educational purposes.