3

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
max66
  • 65,235
  • 10
  • 71
  • 111
user3667111
  • 611
  • 6
  • 21

2 Answers2

3

I suggest to use, if your Prolog support it, a Finite Domain solver.

I usually use GProlog and I can obtain what you ask with something like

fd_domain([A, B], 1, 100),
6 #= A + B,
fd_labeling([A, B]),

where fd_domain/3 set the domain for variables A and B (from 1 to 100), 6 #= A + B set the constraint (A + B is 6) and fd_labelling/1 get all possibles calculations.

In Swi-Prolog is a little different.

First of all, you have to load the CLP(FD) library with

:- use_module(library(clpfd)).

To set the variables and the domain, you can write

Vars = [A, B],
Vars ins 1..100,

Setting the constraint is equal

6 #= A + B,

and to get all possible combinations, you can write

label(Vars),
max66
  • 65,235
  • 10
  • 71
  • 111
2

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.