/* Coins puzzle in Picat. Problem from Tony Hürlimann: "A coin puzzle - SVOR-contest 2007" http://www.svor.ch/competitions/competition2007/AsroContestSolution.pdf """ In a quadratic grid (or a larger chessboard) with 31x31 cells, one should place coins in such a way that the following conditions are fulfilled: 1. In each row exactly 14 coins must be placed. 2. In each column exactly 14 coins must be placed. 3. The sum of the quadratic horizontal distance from the main diagonal of all cells containing a coin must be as small as possible. 4. In each cell at most one coin can be placed. The description says to place 14x31 = 434 coins on the chessboard each row containing 14 coins and each column also containing 14 coins. """ Note: This problem is quite hard for CP solvers. A MIP solver solves the 14,31 problem in millis. Model created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. % import cp. % import sat. import mip. % much faster main => go. go => nolog, N = 31, C = 14, time2($coins(N, C)). go2 => nolog, N = 7, C = 4, time2($coins(N, C)). pretty_print(X) => foreach(I in 1..X.length) foreach(J in 1..X[1].length) writef("%d ", X[I,J]) end, nl end. % standard CLP(FD) coins(N,C) => X = new_array(N,N), X :: 0..1, % quadratic horizontal distance Sum :: 0..N*N*N, Sum #= sum([(X[I,J] * abs(I-J)*abs(I-J)) : I in 1..N, J in 1..N]), foreach(I in 1..N) C #= sum([X[I,J] : J in 1..N]), % rows C #= sum([X[J,I] : J in 1..N]) % columns end, Vars = X.vars, solve($[min(Sum),report(printf("Sum: %w\n", Sum)), min, updown],Vars), writeln(sum=Sum), pretty_print(X).