Skip to content

Instantly share code, notes, and snippets.

@salva
Last active May 5, 2016 20:37
Show Gist options
  • Save salva/5275ded4a942bca264395181f2fd6903 to your computer and use it in GitHub Desktop.
Save salva/5275ded4a942bca264395181f2fd6903 to your computer and use it in GitHub Desktop.
Michał Wojciechowski's puzzle (blogs.perl.org/users/michal_wojciechowski/2016/05/brutally-solving-a-logic-puzzle-with-perl-6.html)
$ swipl
?- ["puzzle.prolog"].
true.
?- S = [_, 3, 17, 5, _, _, 13, _, 7], puzzle(S, O).
S = [41, 3, 17, 5, 23, 19, 13, 11, 7],
O = [61, 47, 31, 59, 37, 43, 71, 53, 541] ;
S = [11, 3, 17, 5, 41, 37, 13, 23, 7],
O = [31, 83, 43, 29, 67, 61, 59, 71, 601] ;
S = [11, 3, 17, 5, 41, 37, 13, 53, 7],
O = [31, 83, 73, 29, 97, 61, 59, 71, 691] ;
S = [11, 3, 17, 5, 41, 43, 13, 53, 7],
O = [31, 89, 73, 29, 97, 67, 59, 71, 709] ;
false.
?-
:- use_module(library(clpfd)).
%% A B C
%% D E F
%% G H I
primes([2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,
79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,
167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,
257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,
353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,
449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,
563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,
653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,
761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,
877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,
991,997]).
primes_domain(PD) :-
primes(P),
primes_domain(P, PD).
primes_domain([], 2).
primes_domain([H|T], H \/ D1) :-
primes_domain(T, D1).
puzzle(S, [R1, R2, R3, C1, C2, C3, D1, D2, T]) :-
S = [A, B, C, D, E, F, G, H, I],
[R1, R2, R3, C1, C2, C3, D1, D2 | S] ins 1..100,
primes_domain(PD),
[R1, R2, R3, C1, C2, C3, D1, D2, T | S] ins PD,
all_distinct([R1, R2, R3, C1, C2, C3, D1, D2 | S]),
A + B + C #= R1,
D + E + F #= R2,
G + H + I #= R3,
A + D + G #= C1,
B + E + H #= C2,
C + F + I #= C3,
A + E + I #= D1,
G + E + C #= D2,
R1 + R2 + R3 + C1 + C2 + C3 + D1 + D2 + A + B + C + D + E + F + G + H + I #= T,
labeling([], S).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment