Mastermind in Ruby for The Odin Project
- 12 rows of 4 large holes (codes) and 4 smaller holes (clues)
- 6 different colors (1 to 6)
- Will be placed on the decoding board
- black: correct color and position
- white: correct color
- blank: incorrect color or position
2 players alternate as codemaker and codebreaker
Choses a pattern of four code pegs. Blanks and duplicates may be allowed. Each guess is responded with the key pegs. The codemaker gets one point for each guess the codebreaker makes. An extra point is earned by the codemaker if the codebreaker is unable to guess the exact pattern within the given number of turns.
Makes a guess combination each round.
12 rounds Guesses and feedback alternate until end of rounds.
When the codebreaker finds the right combination (codebreaker wins) or all the rows on the decoding board are full.
From Stack Overflow
Knuth answers this in The Computer as Master Mind and acknowledges that it's hard to define it exactly. He suggests this:
- Calculate the number of blacks by comparing each position in the answer with the same position in the current guess.
- Calculate the number of whites plus blacks as below.
- Subtract (1) from (2) to get the number of whites.
To calculate whites plus blacks:
- Make two arrays,
ans
andguess
, with a slot for each color. - For each color, populate
ans
with the number of pegs of that color in the answer. Similarly, populateguess
with the number of pegs of that color in the current guess. - Add up
min(ans[i], guess[i])
for each i. This is whites plus blacks. ([ans[i], guess[i]].min
in Ruby).
- Create the list 1111,...,6666 of all candidate secret codes
- Start with 1122.
- Repeat the following 2 steps:
- After you got the answer (number of red and number of white pegs) eliminate from the list of candidates all codes that would not have produced the same answer if they were the secret code.
- Pick the first element in the list and use it as new guess.
This averages no more than 5 guesses.