Constraint programming is a style of programming where relations between variables are stated in the form of constraints. Constraints differ from the common primitives of other programming languages in that they do not specify a step or sequence of steps to execute but rather the properties of a solution to be found. If you want use a constraint-specific programming language, you should consider something like Prolog. If however you like Groovy but want to apply a touch of constraint style magic to your code, read on to learn about Gecode/J and Choco.
Gecode/J is a Java interface for the Gecode C++ constraint programming library. Let's have a look at making the Money example from the Gecode/J library a bit Groovier. If you haven't seen the example before, it involves solving the following puzzle:
How can I replace the letters in the puzzle with numbers so that the numbers add up in the expected way. See here for further details.
A little helper library
First we create a little helper library to make our Groovy code a little cleaner:
A Groovy Solution
Here is how we could code the solution.
It relies on the same
Options class used in the original example.
Running this code (we used the latest HEAD version of Groovy on Java 6 with the following JVM argument,
Running the program with the
-gui command line argument yields the following GUI display:
It would be fun to take the example a little further with a proper DSL to define the constraints.
Choco is a java library for constraint satisfaction problems (CSP), constraint programming (CP) and explanation-based constraint solving (e-CP). It is built on a event-based propagation mechanism with backtrackable structures. It's a great alternative to Gecode/J especially if you want a Java only solution.
Choco Magic Squares
And has this output: