/*     
Problem:

There are five consecutive houses, each of a different
color and inhabited by men of different nationalities. They each
own a different pet, have a different favorite drink and drive a
different car.

1.   The Englishman lives in the red house.
2.   The Spaniard owns the dog.
3.   Coffee is drunk in the green house.
4.   The Ukrainian drinks tea.
5.   The green house is immediately to the right of the ivory house.
6.   The Porsche driver owns snails.
7.   The Masserati is driven by the man who lives in the yellow house.
8.   Milk is drunk in the middle house.
9.   The Norwegian lives in the first house on the left.
10.  The man who drives a Saab lives in the house next to the man
     with the fox.
11.  The Masserati is driven by the man in the house next to the
     house where the horse is kept.
12.  The Honda driver drinks orange juice.
13.  The Japanese drives a Jaguar.
14.  The Norwegian lives next to the blue house.

The problem is: Who owns the Zebra?  Who drinks water?
*/

/* Solution, based on one by M. H. van Emden */

/* each house is structured like this 

   [Color,Nationality,Car,Drink,Pet]

   S is the list of 5 houses
*/


zebraOwner(X) :- solve(S), member([_, X, _, _, zebra], S).

waterDrinker(X) :- solve(S), member([_, X, _, water, _], S).


% solve(S) creates the list of houses as a solution.

solve(S) :-
               [_,_,[_,_,_,milk,_],_,_]           = S,  % clue 8
               [[_,norwegian,_,_,_],_,_,_,_]      = S , % clue 9
       member( [green,_,_,coffee,_],                S), % clue 3
       member( [red,englishman,_,_,_],              S), % clue 1
       member( [_,ukranian,_,tea,_],                S), % clue 4
       member( [yellow,_,masserati,_,_],            S), % clue 7
       member( [_,_,honda,orange_juice,_],          S), % clue 12
       member( [_,japanese,jaguar,_,_],             S), % clue 13
       member( [_,spaniard,_,_,dog],                S), % clue 2
       member( [_,_,porsche,_,snails],              S), % clue 6
   left_right( [ivory,_,_,_,_],    [green,_,_,_,_], S), % clue 5
      next_to( [_,norwegian,_,_,_],[blue,_,_,_,_],  S), % clue 14
      next_to( [_,_,masserati,_,_],[_,_,_,_,horse], S), % clue 11
      next_to( [_,_,saab,_,_],     [_,_,_,_,fox],   S), % clue 10
         true.

% member(X, L) is true when X is a member of list L.

member(X, [X|_]).

member(X, [_|L]) :- member(X, L).


% left_right(L, R, X) is true when L is to the immediate left of R in list X

left_right(L, R, [L, R | _]).

left_right(L, R, [_ | X]) :- left_right(L, R, X).


% next_to(X, Y, L) is true when X and Y are next to each other in list L

next_to(X, Y, L) :- left_right(X, Y, L).

next_to(X, Y, L) :- left_right(Y, X, L).


:- nl,
   write('The zebra is owned by the '),
   zebraOwner(X),
   write(X),
   write('.'),
   nl,
   nl.

:- nl,
   write('Water is drunk by the '),
   waterDrinker(X),
   write(X),
   write('.'),
   nl,
   nl.



   