This example concerns five couples and their wedding days. It requires three matrices:
Red dots and blue and green crosses follow as before from the constrains stated in the program below. The black crosses are projected by the dots into corresponding matrix positions; e.g., Vern cannot marry on Wednesday or Friday (vertical), therefore Fran cannot either (horizontal). Once the last constraint is considered, the solution (circles) follows.
Here is the program as a table:
# Sample Logic Problem, p.5, Penny Press, Original Logic Problems, June 2002 wife anne cathy eve fran ida husband paul rob stan vern wally day 1 2 3 4 5 %% # Anne was married on Monday, but not to Wally. wife,day a(anne, 1). wife,husband b(anne, X) :- X \= wally. # Stan's wedding was on Wednesday. Rob was married on Friday, but not to Ida. husband,day c(stan, 3). husband,day d(rob, 5). husband,wife e(rob, X) :- X \= ida. # Vern (who married Fran) was married the day after Eve. husband,wife f(vern, fran). husband,day wife,day g(vern, X, eve, Y) :- X is Y + 1.
The new type of constraint concerns the day after . Prolog can perform arithmetic on integer and floating point numbers. Therefore, the days are represented as integer values. is works like the match operator = , but it evaluates an argument if needed.
Constraint g needs to be checked for all combinations of values for husband and wife . In each case the value for day from the same tuple must be available.
puzzle2pl can enumerate property combinations from more then one tuple. The property names within one tuple are joined by commas and no white space, the tuples are separated by white space. The constraint check in solve is generated as
( g(Husband1, Day1, Wife1, Day1);
...
g(Husband1, Day1, Wife5, Day5);
g(Husband2, Day2, Wife1, Day1);
...
g(Husband2, Day2, Wife5, Day5);
g(Husband3, Day3, Wife1, Day1);
...
g(Husband5, Day5, Wife5, Day5) )
Once again there is a lot of room for optimization in the Prolog code, but the table is simple to comprehend.
The puzzle has a single solution:
$ puzzle2pl sample.puzzle > tmp.pl $ pl ?- ['tmp.pl']. ?- main. anne paul 1 cathy rob 5 eve stan 3 fran vern 4 ida wally 2 no