That Giant’s Causeway puzzle in Prolog
Tuesday, 13th January, 2015
Chris Lamb published a very nice blog post the other day showing a wooden logic puzzle he’d found, and implementing a solver in Python.
– https://chris-lamb.co.uk/posts/giants-causeway-puzzle
It was such a nice post I thought I’d write one in Prolog. Here it is (and in a gist):
% hex tiles puzzle % - https://chris-lamb.co.uk/posts/giants-causeway-puzzle % - https://llaisdy.wordpress.com/2015/01/13/that-giants-causeway-puzzle-in-prolog/ :- use_module(library(clpfd)). %% for all_different/1 %% tile(Name, Colours). % tiles from picture % tile(11, [red, blue, black, yellow, green, white]). % tile(22, [white, black, yellow, green, blue, red]). % tile(33, [green, blue, black, yellow, red, white]). % tile(44, [white, black, red, green, blue, yellow]). % tile(55, [white, blue, green, yellow, black, red]). % tile(66, [white, yellow, red, blue, black, green]). % tile(77, [red, yellow, green, black, blue, white]). % re-jigged a bit tile(11, [white, black, red, green, blue, yellow]). tile(22, [white, black, yellow, green, blue, red]). tile(33, [white, blue, green, yellow, black, red]). tile(44, [white, green, blue, black, yellow, red]). tile(55, [white, red, blue, black, yellow, green]). tile(66, [white, red, yellow, green, black, blue]). tile(77, [white, yellow, red, blue, black, green]). %% only six rotations allowed rotation(0). rotation(1). rotation(2). rotation(3). rotation(4). rotation(5). %% rotate(List1, NStepsAntiClockwise, List2). rotate(Cs, 0, Cs). rotate([A,B,C,D,E,F], 1, [B,C,D,E,F,A]). rotate([A,B,C,D,E,F], 2, [C,D,E,F,A,B]). rotate([A,B,C,D,E,F], 3, [D,E,F,A,B,C]). rotate([A,B,C,D,E,F], 4, [E,F,A,B,C,D]). rotate([A,B,C,D,E,F], 5, [F,A,B,C,D,E]). %% colour(Name, Rotation, Position, Colour). colour(N, R, P, C):- rotation(R), tile(N, Cs), X is (P + R) mod 6, nth0(X, Cs, C). same_colour(N1, R1, P1, N2, R2, P2):- colour(N1, R1, P1, C), colour(N2, R2, P2, C). solve(N1, R1, N2, R2, N3, R3, N4, R4, N5, R5, N6, R6, N7, R7):- all_different([N1, N2, N3, N4, N5, N6, N7]), same_colour(N1, R1, 3, N2, R2, 0), same_colour(N1, R1, 4, N4, R4, 1), same_colour(N1, R1, 5, N3, R3, 2), same_colour(N2, R2, 4, N5, R5, 1), same_colour(N2, R2, 5, N4, R4, 2), same_colour(N3, R3, 3, N4, R4, 0), same_colour(N3, R3, 4, N6, R6, 1), same_colour(N4, R4, 3, N5, R5, 0), same_colour(N4, R4, 4, N7, R7, 1), same_colour(N4, R4, 5, N6, R6, 2), same_colour(N5, R5, 5, N7, R7, 2), same_colour(N6, R6, 3, N7, R7, 0). show(N, R):- tile(N, Cs), rotate(Cs, R, Rs), format("~d ~w~n", [N, Rs]). solve:- solve(N1, R1, N2, R2, N3, R3, N4, R4, N5, R5, N6, R6, N7, R7), show(N1, R1), show(N2, R2), format("---~n"), show(N3, R3), show(N4, R4), show(N5, R5), format("---~n"), show(N6, R6), show(N7, R7).