/*
Magic squares and cards in Picat.
Martin Gardner (July 1971)
"""
Allowing duplicates values, what is the largest constant sum for an order-3
magic square that can be formed with nine cards from the deck.
"""
Model created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
import cp.
main => go.
go =>
N = 3,
X = new_array(N,N),
Vars = vars(X),
Vars :: 1..13,
S :: 0..13*4, % the sum
% there are 4 cards of each value in a deck
foreach(I in 1..13) count(I, Vars,#=<,4) end,
% the standard magic square constraints (sans all_different)
foreach(C in 1..N) sum([X[R,C] : R in 1..N]) #= S end,
foreach(R in 1..N) sum([X[R,C] : C in 1..N]) #= S end,
sum([X[I,I] : I in 1..N]) #= S,
sum([X[I,N+1-I] : I in 1..N]) #= S,
Vars2 = Vars ++ [S],
solve([$max(S)], Vars2),
% solve(Vars2),
writeln(s=S),
foreach(Row in X) writeln(Row.to_list()) end,
nl.