I'm interested in coming up with an algorithm to solve a guessing game. The player is attempting to guess a sequence of 4 unique numbers from 1 to 9. After a guess, they are told how many numbers of their guess are correct and in the correct position and how many are correct and in the wrong position.
The approach I'm taking is to have a starting collection of all of the possible guesses and a collection of all the possible numbers. The collection of guesses is used to give the player an idea of all valid guesses remaining. The collection of numbers stores information about each digit:
- whether it is definitely present or definitely not, and
- which position it is definitely in or definitely not in.
Then, as the player is given more clues, I remove all guesses that must be invalid and update assumptions about the digits. The idea is that, after a certain number of guesses, the algorithm should continue to improve their odds of choosing the correct sequence.
I want to accomplish the process of striking items off of the list and making assumptions about the digits by creating rules. Whenever a rule's conditions are met, the number collection and/or guess collection should update. Rules should include:
- if the current guess has no numbers in the correct position, all numbers in the sequence are definitely not in their current position,
- if 4 of the numbers in the sequence are present, then all guesses without all 4 of these numbers are invalid,
- if two guesses have 8 unique numbers between them and the sum of present numbers is only 3, then the 9th digit not guessed is definitely present,
- etc.
I like the idea that I, as the developer, can continue to add rules as I discover patterns that I have not noticed (or have not been able to formalize) without much hassle. The problem lies in implementation.
Is there a programming pattern that allows me to make an extendable set of rules to test for and react to?