# Solving a puzzle with constraint programming

Constraint programming can get some getting used to. In the usual programming frame of mind (whether with functional or imperative languages) you think of the algorithm and specify to the computer, via your code, exactly what steps to go through in order to solve the problem.

With constraint programming, you don’t tell the computer what to do. You describe in detail the nature of the problem and the computer does the rest.

Einstein’s riddle is usually given as an example to be solved with constraint programming, but to be different, I’ll show something a bit trickier. This is the problem (it’s named “Meeting the Challenge”):

Eight married couples meet to lend one another some books. Couples have the same surname, employment and car. Each couple has a favourite colour. Furthermore we know the following facts:

1. Daniella Black and her husband work as Shop-Assistants.
2. The book “The Seadog” was brought by a couple who drive a Fiat and love the colour red.
3. Owen and his wife Victoria like the colour brown.
4. Stan Horricks and his wife Hannah like the colour white.
5. Jenny Smith and her husband work as Warehouse Managers and they drive a Wartburg.
6. Monica and her husband Alexander borrowed the book “Grandfather Joseph”.
7. Mathew and his wife like the colour pink and brought the book “Mulatka Gabriela”.
8. Irene and her husband Oto work as Accountants.
9. The book “We Were Five” was borrowed by a couple driving a Trabant.
10. The Cermaks are both Ticket-Collectors who brought the book “Shed Stoat”.
11. Mr and Mrs Kuril are both Doctors who borrowed the book “Slovacko Judge”.
12. Paul and his wife like the colour green.
13. Veronica Dvorak and her husband like the colour blue.
14. Rick and his wife brought the book “Slovacko Judge” and they drive a Ziguli.
15. One couple brought the book “Dame Commissar” and borrowed the book “Mulatka Gabriela”.
16. The couple who drive a Dacia, love the colour violet.
17. The couple who work as Teachers borrowed the book “Dame Commissar”.
18. The couple who work as Agriculturalists drive a Moskvic.
19. Pamela and her husband drive a Renault and brought the book “Grandfather Joseph”.
20. Pamela and her husband borrowed the book that Mr and Mrs Zajac brought.
21. Robert and his wife like the colour yellow and borrowed the book “The Modern Comedy”.
22. Mr and Mrs Swain work as Shoppers.
23. “The Modern Comedy” was brought by a couple driving a Skoda.

Who likes Violet? And can you find out everything about everyone from this?

A constraint programming solution, using Choco is given below. This should give you some insight into the nature of this type of problem solving.

```import static choco.Choco.*;
import choco.cp.model.CPModel;
import choco.cp.solver.CPSolver;
import choco.kernel.model.variables.integer.*;
import choco.kernel.solver.variables.integer.IntDomainVar;
import java.util.HashMap;

public class Meeting
{
public static void main(String[] args)
{
int nElements = 8;

String[] _attr = { "SURNAME", "EMPLOYMENT", "CAR", "COLOR", "MAN", "WIFE", "LENT", "BORROWED" };
int SURNAME = 0; int EMPLOYMENT = 1; int CAR = 2; int COLOR = 3;
int MAN  = 4; int WIFE = 5; int LENT = 6; int BORROWED = 7;

String[] Surname = { "Black", "Horricks", "Smith", "Cermaks", "Kuril", "Dvorak", "Swain", "Zajac" };
int BLACK = 0; int HORRICKS = 1; int SMITH = 2; int CERMAKS = 3; int KURIL = 4;
int DVORAK = 5; int SWAIN = 6; int ZAJAC = 7;

String[] Employment = { "Shop-Assistants", "Warehouse Managers", "Accountants", "Ticket-Collectors",
"Doctors", "Teachers", "Agriculturalists", "Shoppers" };
int SHOP_ASSISTANTS = 0; int WAREHOUSE_MANAGERS = 1; int ACCOUNTANTS = 2;
int TICKET_COLLECTORS = 3; int DOCTORS = 4; int TEACHERS = 5; int AGRICULTURALISTS = 6;
int SHOPPERS = 7;

String[] Car = { "Fiat", "Wartburg", "Trabant", "Ziguli", "Dacia", "Moskvic", "Renault", "Skoda" };
int FIAT = 0; int WARTBURG = 1; int TRABANT = 2; int ZIGULI = 3; int DACIA = 4;
int MOSKVIC = 5; int RENAULT = 6; int SKODA = 7;

String[] Color = { "red", "brown", "white", "pink", "green", "blue", "violet", "yellow" };
int RED = 0; int BROWN = 1; int WHITE = 2; int PINK = 3; int GREEN = 4;
int BLUE = 5; int VIOLET = 6; int YELLOW = 7;

String Man[] = { "Owen", "Stan", "Alexander", "Mathew", "Oto", "Paul", "Rick", "Robert"  };
int OWEN = 0; int STAN = 1; int ALEXANDER = 2; int MATHEW = 3; int OTO  = 4;
int PAUL = 5; int RICK = 6; int ROBERT = 7;

String[] Wife     = { "Daniella", "Victoria", "Hannah", "Jenny", "Monica", "Irene", "Veronica", "Pamela" };
int DANIELLA = 0; int VICTORIA = 1; int HANNAH = 2; int JENNY = 3; int MONICA  = 4;
int IRENE = 5; int VERONICA = 6; int PAMELA = 7;

String[] Books = { "The Seadog", "Mulatka Gabriela", "Shed Stoat", "Slovacko Judge", "Dame Commissar",
"Grandfather Joseph", "The Modern Comedy", "We Were Five" };
int THE_SEADOG = 0; int MULATKA_GABRIELA = 1; int SHED_STOAT = 2; int SLOVACKO_JUDGE = 3;
int DAME_COMMISSAR = 4; int GRANDFATHER_JOSEPH = 5; int THE_MODERN_COMEDY = 6;
int WE_WERE_FIVE = 7;

String attvals[][] = { Surname, Employment, Car, Color, Man, Wife, Books, Books };

CPModel model = new choco.cp.model.CPModel();

// We'll assume the couples are numbered 0 to 7.
// The value of the variable represents the couple belongs to,
// i.e if x[SURNAME][BLACK] is 6 then couple with surname Black is couple number 6).

IntegerVariable[][] x = new IntegerVariable[nElements][nElements];
for (int i=0; i<nElements; i++)
{
x[i] = choco.Choco.makeIntVarArray( _attr[i], nElements, 0, nElements-1);
// For a given attribute, Each different attribute value belongs to a
// different couple number.
}

//1.  Daniella Black and her husband work as Shop-Assistants.
x[EMPLOYMENT][SHOP_ASSISTANTS] ));

x[EMPLOYMENT][SHOP_ASSISTANTS] ));

//2.  The book "The Seadog" was brought by a couple who drive a Fiat and love the color red.
x[CAR][FIAT] ));

x[COLOR][RED] ));

//3.  Owen and his wife Victoria like the color brown.
x[WIFE][VICTORIA] ));

x[COLOR][BROWN] ));

//4.  Stan Horricks and his wife Hannah like the color white.
x[WIFE][HANNAH] ));

x[COLOR][WHITE] ));

//5.  Jenny Smith and her husband work as Warehouse Managers and they drive a Wartburg.
x[SURNAME][SMITH] ));

x[EMPLOYMENT][WAREHOUSE_MANAGERS] ));

x[CAR][WARTBURG] ));

//6.  Monica and her husband Alexander borrowed the book "Grandfather Joseph".
x[MAN][ALEXANDER] ));

x[BORROWED][GRANDFATHER_JOSEPH] ));

//7.  Mathew and his wife like the color pink and brought the book "Mulatka Gabriela".
x[COLOR][PINK] ));

x[LENT][MULATKA_GABRIELA] ));

//8.  Irene and her husband Oto work as Accountants.
x[WIFE][IRENE] ));

x[EMPLOYMENT][ACCOUNTANTS] ));

//9.  The book "We Were Five" was borrowed by a couple driving a Trabant.
x[CAR][TRABANT] ));

//10. The Cermaks are both Ticket-Collectors who brought the book "Shed Stoat".
x[EMPLOYMENT][TICKET_COLLECTORS] ));

x[LENT][SHED_STOAT] ));

//11. Mr and Mrs Kuril are both Doctors who borrowed the book "Slovacko Judge".
x[EMPLOYMENT][DOCTORS] ));

x[BORROWED][SLOVACKO_JUDGE] ));

//12. Paul and his wife like the color green.
x[COLOR][GREEN] ));

//13. Veronica Dvorak and her husband like the color blue.
x[WIFE][VERONICA] ));

x[COLOR][BLUE] ));

//14. Rick and his wife brought the book "Slovacko Judge" and they drive a Ziguli.
x[WIFE][VERONICA] ));

x[LENT][SLOVACKO_JUDGE] ));

x[CAR][ZIGULI] ));

//15. One couple brought the book "Dame Commissar" and borrowed the book "Mulatka Gabriela".
x[BORROWED][MULATKA_GABRIELA] ));

//16. The couple who drive a Dacia, love the color violet.
x[COLOR][VIOLET] ));

//17. The couple who work as Teachers borrowed the book "Dame Commissar".
x[BORROWED][DAME_COMMISSAR] ));

//18. The couple who work as Agriculturalists drive a Moskvic.
x[CAR][MOSKVIC] ));

//19. Pamela and her husband drive a Renault and brought the book "Grandfather Joseph".
x[CAR][RENAULT] ));

x[LENT][GRANDFATHER_JOSEPH] ));

//20. Pamela and her husband borrowed the book that Mr and Mrs Zajac brought.
for (int book = 0; book<nElements; book++)
x[BORROWED][book] ),
eq( x[SURNAME][ZAJAC],
x[LENT][book])));

//21. Robert and his wife like the color yellow and borrowed the book "The Modern Comedy".
x[COLOR][YELLOW] ));

x[BORROWED][THE_MODERN_COMEDY] ));

//22. Mr and Mrs Swain work as Shoppers.
x[EMPLOYMENT][SHOPPERS] ));

//23. "The Modern Comedy" was brought by a couple driving a Skoda.
x[CAR][SKODA] ));

// Create the solver
CPSolver solver = new CPSolver();

// solver.solve();
solver.solveAll();

if (!solver.isFeasible())
return;

int colWidth[] = calcAttrWidths(_attr, attvals);

do
{
IntDomainVar[][]  s = new IntDomainVar[nElements][nElements];
HashMap<Integer, String[]> couples = new HashMap<Integer, String[]>();

System.out.print( "         ");
for (int i=0; i<nElements; i++)
{
s[i] = solver.getVar( x[i] );
couples.put( i, new String[ nElements ] );
}
System.out.println();

for (int i=0; i<nElements; i++) // iterate over attributes
for (int j=0; j<nElements; j++)  // iterate over attribute values
{
//  s[i][j].getVal() is the couple number where attribute i
//              has an attribute value of j

int coupleNumber = s[i][j].getVal();
String[] attrs = couples.get( coupleNumber );
attrs[i] =  attvals[i][j];
}

for (int couple=0; couple<nElements; couple++)
{
System.out.print( "couple " + (couple+1) + ":" );
String[] attrs = couples.get( couple );
for (int attr=0; attr<nElements; attr++)
System.out.print( padRight( attrs[ attr ], colWidth[ attr ] ) );
System.out.println();
}
System.out.println("---------------------");
solver.printRuntimeStatistics();
}
while (solver.nextSolution() == Boolean.TRUE);
}

public static String padRight(String s, int n)
{
return String.format("%1\$-" + n + "s", s);
}

public static int[] calcAttrWidths(  String[] attrs, String[][] attvals )
{
int nElements = attrs.length;
int[] atmax = new int[ nElements ];
for (int i=0; i<nElements; i++)
atmax[i] = attrs[i].length()+1;

for (int i=0; i<nElements; i++)
{
int max = atmax[i];
for (int j=0; j<nElements; j++)
{
int lenVal = attvals[i][j].length();
if ( max < lenVal )
max = lenVal;
}
atmax[i] = max + 1;
}
return atmax;
}

}```

1. journeyLIU

The above code is no longer supported by choco 4.
So I revise it with the latest usage of choco 4 (http://www.choco-solver.org/).
I encounter the NullpointerException problem in constraint numbered 20.
(that is Pamela and her husband borrowed the book that Mr and Mrs Zajac brought)
However, marking it out will success to run and solve the puzzle.
Code:

import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solution;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.search.strategy.Search;
import org.chocosolver.solver.variables.IntVar;

public class Meeting {
public static void main(String[] args) {

int nElements = 8;

String[] _attr = { “SURNAME”, “EMPLOYMENT”, “CAR”, “COLOR”, “MAN”, “WIFE”, “LENT”, “BORROWED” };
int SURNAME = 0; int EMPLOYMENT = 1; int CAR = 2; int COLOR = 3;
int MAN = 4; int WIFE = 5; int LENT = 6; int BORROWED = 7;

String[] Surname = { “Black”, “Horricks”, “Smith”, “Cermaks”, “Kuril”, “Dvorak”, “Swain”, “Zajac” };
int BLACK = 0; int HORRICKS = 1; int SMITH = 2; int CERMAKS = 3; int KURIL = 4;
int DVORAK = 5; int SWAIN = 6; int ZAJAC = 7;

String[] Employment = { “Shop-Assistants”, “Warehouse Managers”, “Accountants”, “Ticket-Collectors”,
“Doctors”, “Teachers”, “Agriculturalists”, “Shoppers” };
int SHOP_ASSISTANTS = 0; int WAREHOUSE_MANAGERS = 1; int ACCOUNTANTS = 2;
int TICKET_COLLECTORS = 3; int DOCTORS = 4; int TEACHERS = 5; int AGRICULTURALISTS = 6;
int SHOPPERS = 7;

String[] Car = { “Fiat”, “Wartburg”, “Trabant”, “Ziguli”, “Dacia”, “Moskvic”, “Renault”, “Skoda” };
int FIAT = 0; int WARTBURG = 1; int TRABANT = 2; int ZIGULI = 3; int DACIA = 4;
int MOSKVIC = 5; int RENAULT = 6; int SKODA = 7;

String[] Color = { “red”, “brown”, “white”, “pink”, “green”, “blue”, “violet”, “yellow” };
int RED = 0; int BROWN = 1; int WHITE = 2; int PINK = 3; int GREEN = 4;
int BLUE = 5; int VIOLET = 6; int YELLOW = 7;

String Man[] = { “Owen”, “Stan”, “Alexander”, “Mathew”, “Oto”, “Paul”, “Rick”, “Robert” };
int OWEN = 0; int STAN = 1; int ALEXANDER = 2; int MATHEW = 3; int OTO = 4;
int PAUL = 5; int RICK = 6; int ROBERT = 7;

String[] Wife = { “Daniella”, “Victoria”, “Hannah”, “Jenny”, “Monica”, “Irene”, “Veronica”, “Pamela” };
int DANIELLA = 0; int VICTORIA = 1; int HANNAH = 2; int JENNY = 3; int MONICA = 4;
int IRENE = 5; int VERONICA = 6; int PAMELA = 7;

String[] Books = { “The Seadog”, “Mulatka Gabriela”, “Shed Stoat”, “Slovacko Judge”, “Dame Commissar”,
“Grandfather Joseph”, “The Modern Comedy”, “We Were Five” };
int THE_SEADOG = 0; int MULATKA_GABRIELA = 1; int SHED_STOAT = 2; int SLOVACKO_JUDGE = 3;
int DAME_COMMISSAR = 4; int GRANDFATHER_JOSEPH = 5; int THE_MODERN_COMEDY = 6;
int WE_WERE_FIVE = 7;

String attvals[][] = { Surname, Employment, Car, Color, Man, Wife, Books, Books };

Model model = new Model();

// We’ll assume the couples are numbered 0 to 7.
// The value of the variable represents the couple belongs to,
// i.e if x[SURNAME][BLACK] is 6 then couple with surname Black is couple number 6).

IntVar[][] x = new IntVar[nElements][nElements];
for (int i=0; i<nElements; i++)
{
x[i] = model.intVarArray( _attr[i], nElements, 0, nElements-1);
// For a given attribute, Each different attribute value belongs to a
// different couple number.
model.allDifferent(x[i]).post();
}

//1. Daniella Black and her husband work as Shop-Assistants.
System.out.println(x[1][1]);
x[SURNAME][BLACK].eq(x[EMPLOYMENT][SHOP_ASSISTANTS]).post();
x[WIFE][DANIELLA].eq(x[EMPLOYMENT][SHOP_ASSISTANTS]).post();

//2. The book "The Seadog" was brought by a couple who drive a Fiat and love the color red.

//3. Owen and his wife Victoria like the color brown.
x[MAN][OWEN].eq(x[WIFE][VICTORIA]).post();
x[MAN][OWEN].eq(x[COLOR][BROWN]).post();

//4. Stan Horricks and his wife Hannah like the color white.
x[MAN][STAN].eq(x[WIFE][HANNAH]).post();
x[MAN][STAN].eq(x[COLOR][WHITE]).post();

//5. Jenny Smith and her husband work as Warehouse Managers and they drive a Wartburg.
x[WIFE][JENNY].eq(x[SURNAME][SMITH]).post();
x[WIFE][JENNY].eq(x[EMPLOYMENT][WAREHOUSE_MANAGERS]).post();
x[WIFE][JENNY].eq(x[CAR][WARTBURG]).post();

//6. Monica and her husband Alexander borrowed the book "Grandfather Joseph".
x[WIFE][MONICA].eq(x[MAN][ALEXANDER]).post();
x[WIFE][MONICA].eq(x[BORROWED][GRANDFATHER_JOSEPH]).post();

//7. Mathew and his wife like the color pink and brought the book "Mulatka Gabriela".
x[MAN][MATHEW].eq(x[COLOR][PINK]).post();
x[MAN][MATHEW].eq(x[LENT][MULATKA_GABRIELA]).post();

//8. Irene and her husband Oto work as Accountants.
x[MAN][OTO].eq(x[WIFE][IRENE]).post();
x[MAN][OTO].eq(x[EMPLOYMENT][ACCOUNTANTS]).post();

//9. The book "We Were Five" was borrowed by a couple driving a Trabant.
x[BORROWED][WE_WERE_FIVE].eq(x[CAR][TRABANT]).post();

//10. The Cermaks are both Ticket-Collectors who brought the book "Shed Stoat".
x[SURNAME][CERMAKS].eq(x[EMPLOYMENT][TICKET_COLLECTORS]).post();
x[SURNAME][CERMAKS].eq(x[LENT][SHED_STOAT]).post();

//11. Mr and Mrs Kuril are both Doctors who borrowed the book "Slovacko Judge".
x[SURNAME][KURIL].eq(x[EMPLOYMENT][DOCTORS]).post();
x[SURNAME][KURIL].eq(x[BORROWED][SLOVACKO_JUDGE]).post();

//12. Paul and his wife like the color green.
x[MAN][PAUL].eq(x[COLOR][GREEN]).post();

//13. Veronica Dvorak and her husband like the color blue.
x[SURNAME][DVORAK].eq(x[WIFE][VERONICA]).post();
x[SURNAME][DVORAK].eq(x[COLOR][BLUE]).post();

//14. Rick and his wife brought the book "Slovacko Judge" and they drive a Ziguli.
x[MAN][RICK].eq(x[WIFE][VERONICA]).post();
x[MAN][RICK].eq(x[LENT][SLOVACKO_JUDGE]).post();
x[MAN][RICK].eq(x[CAR][ZIGULI]).post();

//15. One couple brought the book "Dame Commissar" and borrowed the book "Mulatka Gabriela".
x[LENT][DAME_COMMISSAR].eq(x[BORROWED][MULATKA_GABRIELA]).post();

//16. The couple who drive a Dacia, love the color violet.
x[CAR][DACIA].eq(x[COLOR][VIOLET]).post();

//17. The couple who work as Teachers borrowed the book "Dame Commissar".
x[EMPLOYMENT][TEACHERS].eq(x[BORROWED][DAME_COMMISSAR]).post();

//18. The couple who work as Agriculturalists drive a Moskvic.
x[EMPLOYMENT][AGRICULTURALISTS].eq(x[CAR][MOSKVIC]).post();

//19. Pamela and her husband drive a Renault and brought the book "Grandfather Joseph".
x[WIFE][PAMELA].eq(x[CAR][RENAULT]).post();
x[WIFE][PAMELA].eq(x[LENT][GRANDFATHER_JOSEPH]).post();

//20. Pamela and her husband borrowed the book that Mr and Mrs Zajac brought.
// for (int book = 0; book<nElements; book++){
// model.ifOnlyIf(model.arithm(x[WIFE][PAMELA], "==", x[BORROWED][book]), model.arithm(x[SURNAME][ZAJAC], "==", x[LENT][book]));
// }

//21. Robert and his wife like the color yellow and borrowed the book "The Modern Comedy".
x[MAN][ROBERT].eq(x[COLOR][YELLOW]).post();
x[MAN][ROBERT].eq(x[BORROWED][THE_MODERN_COMEDY]).post();

//22. Mr and Mrs Swain work as Shoppers.
x[SURNAME][SWAIN].eq(x[EMPLOYMENT][SHOPPERS]).post();

//23. "The Modern Comedy" was brought by a couple driving a Skoda.
x[LENT][THE_MODERN_COMEDY].eq(x[CAR][SKODA]).post();

// Create the solver // solver.solve();
Solver solver = model.getSolver();

Solution solution = solver.findSolution();
if (solution != null) {
System.out.println(solution.toString());
}

int colWidth[] = calcAttrWidths(_attr, attvals);

do
{
IntVar[][] s = new IntVar[nElements][nElements];
HashMap couples = new HashMap();

System.out.print( ” “);
for (int i=0; i<nElements; i++)
{
s[i] = x[i];
couples.put( i, new String[ nElements ] );
}
System.out.println();

for (int i=0; i<nElements; i++) // iterate over attributes
for (int j=0; j<nElements; j++) // iterate over attribute values
{
// s[i][j].getVal() is the couple number where attribute i
// has an attribute value of j

int coupleNumber = s[i][j].getValue();
String[] attrs = couples.get( coupleNumber );
attrs[i] = attvals[i][j];
}

for (int couple=0; couple<nElements; couple++)
{
System.out.print( "couple " + (couple+1) + ":" );
String[] attrs = couples.get( couple );
for (int attr=0; attr<nElements; attr++)
System.out.print( padRight( attrs[ attr ], colWidth[ attr ] ) );
System.out.println();
}
System.out.println("———————");
solver.showStatistics();
}
while (solver.isSearchCompleted() == Boolean.TRUE);
}
}

• amnon.david@gmail.com

Thanks again ðŸ™‚ I knew there was a new version of Choco and that the API has changed but never got around to learning it. Thanks for your contribution.

2. journeyLIU

I fix the NullPointerException issue by replace “==” with “=”.

//20. Pamela and her husband borrowed the book that Mr and Mrs Zajac brought.
for (int book = 0; book<nElements; book++){
model.ifOnlyIf(model.arithm(x[WIFE][PAMELA], "=", x[BORROWED][book]), model.arithm(x[SURNAME][ZAJAC], "=", x[LENT][book]));
}

• amnon.david@gmail.com

Thank you ðŸ™‚