Search code examples
prologconstraintsconstraint-programmingconstraint-satisfaction

Get Prolog to give all possibilities for arithmetic


I was wondering whether in prolog it is possible to get it to brute force all the possible calculations for something like this:

6 is Z + Q

Z = 1 Q = 5
Z = 2 Q = 4
Z = 3 Q = 3

Solution

  • The generate-and-test approach also works. Of course, you still need some constraints, for example:

    ?- between(1, 6, X), % X is an integer between 1 and 6
       between(1, 6, Y), % Y is an integer between 1 and 6
       X =< Y,           % X is not larger than Y
       X + Y =:= 6.      % the sum is 6
    X = 1, Y = 5 ;
    X = 2, Y = 4 ;
    X = Y, Y = 3 ;
    false.
    

    The order of the subqueries is significant, so you could as well call it generate-then-test. If you are not afraid to hard-code some of the constraints, there might be ways to avoid generating some of the values, and make some of the tests unnecessary, for example:

    ?- between(1, 6, X), % X is an integer between 1 and 6
       between(X, 6, Y), % Y is an integer between X and 6
       X + Y =:= 6.      % the sum is 6
    X = 1, Y = 5 ;
    X = 2, Y = 4 ;
    X = Y, Y = 3 ;
    false.
    

    You should realize that going down that road far enough is about the same as implementing a constraint solver like CLP(FD) for example.