Sergii Dymchenko

Solving PuzzlOR "Coins" puzzle with constraint logic programming

PuzzlOR's problem for February 2015–April 2015 was "Coins": http://puzzlor.com/2015-02_Coins.html

The puzzle asks to find an arrangement of 9 coins (3 of each type – 1, 5, and 10 cents) in the 3 × 3 grid in which sums for each row and column correspond to the numbers given in the picture.

The answer submission deadline has passed, and I want to share my solution to the puzzle, for which I used Prolog-based constraint logic programming system ECLiPSe.

Here is my complete program to solve the puzzle (https://github.com/kit1980/sdymchenko-com/blob/master/coins-eclipse/coins.ecl):

:- lib(ic).
:- lib(ic_global).
main :-
    dim(Coins, [3, 3]),
    Coins :: [1, 5, 10],
    occurrences(1, Coins, 3),
    occurrences(5, Coins, 3),
    occurrences(10, Coins, 3),
    sum(Coins[1, 1..3]) #= 11,
    sum(Coins[2, 1..3]) #= 12,
    sum(Coins[3, 1..3]) #= 25,
    sum(Coins[1..3, 1]) #= 21,
    sum(Coins[1..3, 2]) #= 16,
    sum(Coins[1..3, 3]) #= 11,
    labeling(Coins),
    ( foreacharg(Row, Coins) do
        array_list(Row, List),
        join_string(List, "\t", Line),
        writeln(Line)
    ).

First two lines import 2 constraint programming libraries: ic for arithmetic constraints and ic_global for occurrences. Then 3 by 3 Coins array is declared; the array can only have 1, 5, or 10 as its elements, and each of the numbers must occur 3 times. After that sums of the rows and columns are constrained according to the problem specification, and labeling finds concrete values for Coins array that satisfy all constraints. In the end, foreacharg loop is used to output the answer:

1	5	5
10	1	1
10	10	5

This puzzle is much easier than the previous PuzzlOR's problem, Electrifying, for which I also have a solution in ECLiPSe. For "Coins", any bruteforce solution should work, because there are only about 9! / (3 * 3!) = 1680 variants to check. Still, ECLiPSe allows to formulate the problem declaratively and compactly.

To learn more about ECLiPSe see the official site, Hakan Kjellerstrand's ECLiPSe page, and eclipse-clp tag on this blog.

Comments

comments powered by Disqus