Search code examples
answer-set-programmingclingo

Solving a Logic Puzzle with Answer Set Programming


Disclaimer: I am almost entirely new to clingo, and answer set programming in general.

I am trying to solve a grid logic puzzle using clingo. To start, I want to generate all models that include one instance of each category.

For example, if there are three people: person(a; b; c)., three houses: house(w; x; z)., and three colors: color(r; g; y).

I would want one potential stable model to be assign(a, r, x), assign(b, g, z), assign(c, y, w) and another potential stable model to be assign(a, g, w), assign(b, y, z), assign(c, r, x), etc. That is, each person appears exactly once and likewise for the colors. I figure that once I have these models I can use constraints to eliminate models until the puzzle is solved.

I have tried using choice rules and constraints:

{assign(P, C, H)} :- person(P), color(C), house(H).
P1=P2 :- assign(P1, C, H), assign(P2, C, H).

But this is not quite scalable to large puzzles with many variables. Can anyone advise of a better way of doing this?


Solution

  • Assuming you wanted to write color(r;g;y). how about the following?

    % assign each house exactly one person/color 1 {assign(P, C, H) : person(P), color(C) } 1 :- house(H). % assign each person exactly one house/color 1 {assign(P, C, H) : house(H), color(C) } 1 :- person(P). % assign each color exactly one person/house 1 {assign(P, C, H) : house(H), person(P) } 1 :- color(C).