/* Rotate digits puzzle in Picat. Puzzle #60 from Clessa "Math and logic puzzles for PC enthusiasts": """ In the grid shown, the digits 1–9 are arranged so that the first row added to the second row equals the bottom row (i.e. 583 + 146 = 729). Now if the grid is rotated clockwise at 90 degrees, you will see that the first two rows still add up to the last row (i.e. 715 + 248 = 963). Can you find another combination of the digits 1–9 which has the same property? 5 8 3 7 1 5 1 4 6 2 4 8 7 2 9 9 6 3 """ The two solutions are Matrix: {4,8,2} {1,5,7} {6,3,9} Rotated 90 degrees: {6,1,4} {3,5,8} {9,7,2} Matrix: {5,8,3} {1,4,6} {7,2,9} Rotated 90 degrees: {7,1,5} {2,4,8} {9,6,3} This model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. import util. main => go. go ?=> M = 3, X = new_array(M,M), X :: 1..9, all_different(X.vars), X[1,1]*100 + X[1,2]*10 + X[1,3] + X[2,1]*100 + X[2,2]*10 + X[2,3] #= X[3,1]*100 + X[3,2]*10 + X[3,3], % rotated X[3,1]*100 + X[2,1]*10 + X[1,1] + X[3,2]*100 + X[2,2]*10 + X[1,2] #= X[3,3]*100 + X[2,3]*10 + X[1,3], solve(X), foreach(Row in X) println(Row) end, nl, fail, nl. go => true. % % Using matrix operations (transpose) % go2 ?=> M = 3, X = new_array(M,M), X :: 1..9, all_different(X.vars), to_num(X[1],X1), to_num(X[2],X2), to_num(X[3],X3), X1 + X2 #= X3, XT = X.reverse.transpose, to_num(XT[1],XT1), to_num(XT[2],XT2), to_num(XT[3],XT3), XT1 + XT2 #= XT3, solve(X.vars), println("Matrix:"), foreach(Row in X) println(Row) end, nl, println("Rotated 90 degrees:"), foreach(Row in XT) println(Row) end, nl, nl, fail, nl. go2 => true. % % converts a number Num to/from a list of integer List given a base Base % to_num(List, Base, Num) => Len = length(List), Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]). to_num(List, Num) => to_num(List, 10, Num).