Skip to content

Instantly share code, notes, and snippets.

@afvanwoudenberg
Created March 24, 2023 22:18
Show Gist options
  • Save afvanwoudenberg/cf5d0c4e8f9c28f8cfef301969502a5c to your computer and use it in GitHub Desktop.
Save afvanwoudenberg/cf5d0c4e8f9c28f8cfef301969502a5c to your computer and use it in GitHub Desktop.
A Prolog solver for the Zebra puzzle a.k.a. Einstein's riddle
% A Prolog solver for the Zebra puzzle a.k.a. Einstein's riddle.
% https://en.wikipedia.org/wiki/Zebra_Puzzle
einstein :-
einstein(Solution),
write_sol(Solution).
einstein(Sol) :-
Sol = [
[1,N1,C1,P1,D1,S1], % There are five houses.
[2,N2,C2,P2,D2,S2],
[3,N3,C3,P3,D3,S3],
[4,N4,C4,P4,D4,S4],
[5,N5,C5,P5,D5,S5]],
member([_,englishman,red,_,_,_],Sol), % The Englishman lives in the red house.
member([_,spaniard,_,dog,_,_],Sol), % The Spaniard owns the dog.
member([_,_,green,_,coffee,_],Sol), % Coffee is drunk in the green house.
member([_,ukrainian,_,_,tea,_],Sol), % The Ukrainian drinks tea.
member([GH,_,green,_,_,_],Sol), % The green house is immediately to the right of the ivory house.
member([IH,_,ivory,_,_,_],Sol),
GH =:= IH + 1,
member([_,_,_,snails,_,old_gold],Sol), % The Old Gold smoker owns snails.
member([_,_,yellow,_,_,kools],Sol), % Kools are smoked in the yellow house.
member([3,_,_,_,milk,_],Sol), % Milk is drunk in the middle house.
member([1,norwegian,_,_,_,_],Sol), % The Norwegian lives in the first house.
member([BH,_,_,_,_,chesterfields],Sol), % The man who smokes Chesterfields lives in the house next to the man with the fox.
member([CH,_,_,fox,_,_],Sol),
next_to(BH,CH),
member([DH,_,_,_,_,kools],Sol), % Kools are smoked in the house next to the house where the horse is kept.
member([HH,_,_,horse,_,_],Sol),
next_to(DH,HH),
member([_,_,_,_,orange_juice,lucky_strike],Sol), % The Lucky Strike smoker drinks organge juice.
member([_,japanese,_,_,_,parliaments],Sol), % The Japanese smokes Parliaments
member([NH,norwegian,_,_,_,_],Sol), % The Norwegian lives next to the blue house.
member([BlH,_,blue,_,_,_],Sol),
next_to(NH,BlH),
permutation([englishman,spaniard,ukrainian,japanese,norwegian],[N1,N2,N3,N4,N5]),
permutation([green,ivory,yellow,blue,red],[C1,C2,C3,C4,C5]),
permutation([dog,snails,fox,horse,zebra],[P1,P2,P3,P4,P5]),
permutation([coffee,tea,milk,orange_juice,water],[D1,D2,D3,D4,D5]),
permutation([old_gold,kools,chesterfields,lucky_strike,parliaments],[S1,S2,S3,S4,S5]).
next_to(A,B) :- A =:= B - 1.
next_to(A,B) :- A =:= B + 1.
write_sol(Solution) :-
write('+--+------------+------------+------------+-------------+--------------+'),nl,
maplist(writef('|%2L|%12L|%12L|%12L|%13L|%14L|\n'),Solution),
write('+--+------------+------------+------------+-------------+--------------+'),nl.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment