The Mastermind game |
You probably know the game MasterMind.
The computer guesses a secret code, consisting of four letters, each of which is a letter between 'A' and 'F'. The player has 10 attempts to guess this code. A guess consists again of a four-letter sequence. The computer "grades" this sequence: It indicates how many symbols of the guess are entirely correct (that is, the correct letter in the correct position), and how many symbols are a correct letter, but in the wrong position. For instance, if "ABCD" is the secret code, and the user guesses "CBEA", the grade is "1 positions, 2 letters" (since "B" is entirely correct, while "A" and "C" are correct letters, but in the wrong position).
Your first task is to modify this program by adding a variable
val CODE_LENGTH = 4at the beginning that determines the length of the secret code (and of the player's guesses). The set of letters remains fixed at "A" to "F". Check that your program works correctly when you set the code length to be three, or five.
In my implementation, both the secret code and the player's guesses cannot contain repeated letters. So "ABAD" is not allowed. Your second task is to modify the program so that repeated letters are allowed.
This makes grading the player's guesses much harder. Here are a few examples:
Code | Guess | Grading -----+-------+----------------------------------- ABCD | BAAB | 0 positions, 2 letters ABCD | AFAA | 1 positions, 0 letters ABCD | ACCB | 2 positions, 1 letters ABAB | BABA | 0 positions, 4 letters -----+-------+-----------------------------------To grade a guess, first check which positions are entirely correct. Then remove these letters from both strings, and count how often each letter occurs in the code and in the guess. The number of correct letters is the smaller of the two: For instance, if there are two "A"s in the code and the guess contains one "A", this counts as one correct letter. If there are two "A"s in the code and the guess contains three "A"s, then that counts as two correct letters.
The Mastermind game |