Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
2  
Peter Norvig's article on constraint propagation is a recommended reading. The article uses Sudoku as an example but it is applicable to many types of number filling games as well. –  rwong Feb 27 at 15:10
    
Not a pattern, but there are declarative logic programming languages that would solve these problems nicely. –  Telastyn Feb 27 at 15:13
1  
FYI, this problem is known as "Bulls and Cows", which might help you find relevant resources. –  jonrsharpe Feb 27 at 15:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.