Reputation: 1
I want to find all possible 3x3 magic squares.
Quoting from English wikipedia:
A magic square is an arrangement of distinct numbers (i.e. each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the main and secondary diagonals, all add up to the same number.
Here's one sample solution:
8 1 6
3 5 7
4 9 2
How can I write a Prolog program that finds all solutions without using library(clpfd)
?
Upvotes: 0
Views: 2227
Reputation: 5645
Here is a solution with SWI-Prolog but not clpfd:
square(L) :-
setof(S, carre(S), L).
carre(L) :-
L = [[A, B, C],
[D, E, F],
[G, H, I]],
flatten(L, LF),
numlist(1,9, LN),
init(LF, LN),
15 is A + B + C,
15 is D + E + F,
15 is G + H + I,
15 is A + D + G,
15 is B + E + H,
15 is C + F + I.
init([H|T], L) :-
select(H, L, L1),
init(T, L1).
init([], []).
Upvotes: 3