/* Coins puzzle in Picat using bv module. 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/SAT solvers. A MIP solver solves the 14,31 problem in millis. This model uses the bv module (which is also slow on this problem). Model created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. import sat. import bv_utils. 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].bti) end, nl end. coins(N,C) => % X = new_array(N,N), % X :: 0..1, X = make_bv_matrix(N,N,0,1), % quadratic horizontal distance % Sum :: 0..N*N*N, bv_sum([X[I,J].bv_mul(AbsI_J).bv_mul(AbsI_J) : I in 1..N, J in 1..N, AbsI_J = int_to_bv(abs(I-J))]).bv_eq(Sum), foreach(I in 1..N) bv_sum([X[I,J] : J in 1..N]).bv_eq(C), % rows bv_sum([X[J,I] : J in 1..N]).bv_eq(C) % columns end, Vars = X, println(solve), solve($[min(Sum),report(printf("Sum: %w\n", Sum)), min, updown],Vars), writeln(sum=Sum.bti), pretty_print(X).