i’m trying to solve 2-water jug problem in swi-prolog by implementing this pseudocode:
x, y is current volume of jug X, Y
Vx, Vy is capacity of jug X, Y
and z is the goal volume of liquid
while (x != z and y != z):
if y == 0:
y = Vy
if x == Vx:
x = 0
if y != 0 and x < Vx:
k = min(y, Vx - x)
x = x + k
y = y - k
Here is my Prolog code:
jugY(Y, Vy, Yc) :- ( Y =:= 0
-> Yc is Vy; % Yc is the new volume of jug Y
Yc is Y
).
jugX(X, Vx, Xc) :- ( X =:= Vx
-> Xc is 0; % Xc is the new volume of jug X
Xc is X
).
pouring(Y, X, Vx, K, Xc, Yc) :- ( Y =\= 0, X < Vx
-> K is min(Y, Vx - X)
, Xc is X + K
, Yc is Y - K
).
do(Vy, Vx, Y, X, Yc, Xc, K) :-
jugY(Y, Vy, Yc);
jugX(X, Vx, Xc);
pouring(Yc, Xc, Vx, K, Xc1, Yc1).
loop(Vy, Vx, Y, X, Z, Yc, Xc, K) :-
( X =\= Z, Y =\= Z ),
jugY(Y, Vy, Yc);
jugX(X, Vx, Xc);
pouring(Yc, Xc, Vx, K, Xc1, Yc1),
loop(Vy, Vx, Y, X, Z, Yc, Xc, K).
My 3 conditions work fine. Now i’m stucking at creating the while loop.
This is my query:
?- do(5, 3, 0, 0, Yc, Xc, K).
The predicate do i created to test 1 iteration of the loop. In this predicate, 2 first conditions are executed successfully. But at predicate pouring,i got this error:
Arguments are not sufficiently instantiated
In:
[2] _1450=\=0
[1] pouring(_1506,_1508,3,_1512,_1514,_1516) at line 11
I tried to write the value of Yc and Xc, and it works fine. I don’t know why that error keeps happen.
Can you guys tell me how to fix this error and how to implement this while loop in Prolog.
Thank you so much.