/* Another kind of magic square in Picat. From http://benvitale-funwithnum3ers.blogspot.com/2010/12/another-kind-of-magic-square.html """ We all know this type of Magic Square .... 8 1 6 3 5 7 4 9 2 where the numbers are arranged such that the sum of the numbers in any horizontal, vertical, or main diagonal line is always the same number 8 + 1 + 6 = 8 + 3 + 4 = 8 + 5 + 2 = 15 For normal magic squares of order n = 3, 4, 5, ..., the magic constants are: n(n^2+1)/2 http://oeis.org/A006003 http://mathworld.wolfram.com/MagicSquare.html Now, let's consider a magic square where the numbers 1 to 9 in a 3x3 array so that the numbers surrounding each number add to a multiple of that number. 2 6 5 7 3 1 9 8 4 Notice that 7 + 3 + 6 = 16 (a multiple of 2) 6 + 3 + 1 = 10 (a multiple of 5) 8 + 3 + 1 = 12 (a multiple of 4) 8 + 3 + 7 = 18 (a multiple of 9) """ Notes: 1) this problem don't have the constraint that all rows, columns, and diagonals must sum to the same value. So it is "Another kind" of magic squares. 2) Number of solutions for certain n n = 2: 0 solutions n = 3: 8 solutions (1 solution with Frenicle symmetry) n = 4: 0 solutions This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. main => go. go ?=> nolog, N = 3, Map = get_global_map(), Map.put(count,0), magic(N, Magic), foreach(Row in Magic) println(Row.to_list()) end, nl, Map.put(count, Map.get(count)+1), fail, nl. go => println(num_solutions=get_global_map().get(count)), nl. magic(N, Magic) => Magic = new_array(N,N), Magic :: 1..N*N, Vars = Magic.vars(), all_distinct(Vars), % Symmetry breaking, Frenicle form % Magic[1,1] #= min([Magic[1,1], Magic[1,N], Magic[N,1], Magic[N,N]]), % Magic[1,2] #< Magic[2,1], V = {-1,0,1}, foreach(I in 1..N, J in 1..N) sum([Magic[I+A,J+B] : A in V, B in V, member(I+A, 1..N), member(J+B,1..N)]) mod Magic[I,J] #= 0 end, solve(Vars).