CSP for Java
Home page > CSP4J > CSP4J

CSP4J

Wednesday 6 May 2009, by Julien Vion

CSP4J is a CSP solving API. It is designed to solve quickly and easily combinatorial problems that are parts of Java applications.

Example code for solving the n-queens problem:

  1. public class Queens implements ProblemGenerator {
  2.     private final int size;
  3.     private final Collection<Constraint> constraints;
  4.     private final List<Variable> variables;
  5.     public Queens(int size) {
  6.         this.size = size;
  7.         constraints = new ArrayList<Constraint>();
  8.         variables = new ArrayList<Variable>();
  9.     }
  10.     @Override
  11.     public void generate() {
  12.         final int[] domain = new int[size];
  13.         for (int i = 0; i < size; i++) {
  14.             domain[i] = i;
  15.         }
  16.         for (int i = 0; i < size; i++) {
  17.             variables.add(new Variable(domain));
  18.         }
  19.         for (int i = 0; i < size; i++) {
  20.             for (int j = i + 1; j < size; j++) {
  21.                 final int diff = Math.abs(i - j);
  22.                 constraints.add(new AbstractAC3Constraint(variables
  23.                         .get(i), variables.get(j)) {
  24.                     @Override
  25.                     public boolean check() {
  26.                         return getValue(0) != getValue(1)
  27.                                 && Math
  28.                                         .abs(getValue(0)
  29.                                                 - getValue(1)) != diff;
  30.                     }
  31.                 });
  32.             }
  33.         }
  34.     }
  35.     @Override
  36.     public Collection<Constraint> getConstraints() {
  37.         return constraints;
  38.     }
  39.     @Override
  40.     public List<Variable> getVariables() {
  41.         return variables;
  42.     }
  43.     public static void main(String[] args)
  44.             throws FailedGenerationException, IOException {
  45.         final ProblemGenerator generator = new Queens(Integer
  46.                 .valueOf(args[0]));
  47.         final Solver solver = new MGACIter(Problem.load(generator));
  48.         solver.runSolver();
  49.         for (Variable v : generator.getVariables()) {
  50.             System.out
  51.                     .println(v + ": " + solver.getSolution().get(v));
  52.         }
  53.     }
  54. }
SPIP | template | | Site Map | Follow-up of the site's activity RSS 2.0