-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSOLVING WATER JUG PROBLEM
52 lines (48 loc) · 1.98 KB
/
SOLVING WATER JUG PROBLEM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
AIM:
To write a prolog program to implement water jug problem.
ALGORITHM:
STEP 1: Fill the 4 gallon jug if x<4.
STEP 2: Fill the 3 gallon jug if x<3.
STEP 3: Pour some water out of the 4 gallon jug (if x>0).
STEP 4: Pour some water out of the 3 gallon jug (if x>0).
STEP 5: Empty the 4 gallon jug on the ground (if x>0).
STEP 6: Empty the 3 gallon jug on the ground (if y>0).
STEP 7: Pour the water from the 3 gallon jug into the 4 gallon jug until the 4 gallon jug is full
(if x+y>=4 and y>0).
STEP 8: Pour the water from the 4 gallon jug into the 3 gallon jug until the 3 gallon jug is full
(if x+y>=3 and x>0).
STEP 9: Pour all the water from 3 gallon jug into the 4 gallon jug (if x+y<=4 and y>0).
STEP 10: Pour all the water from 4 gallon jug into the 3 gallon jug (if x+y<=3 and x>0).
PROGRAM:
member(X,[X|_]).
member(X,[Y|Z]):-member(X,Z).
move(X,Y,_):-X=:=2,Y=:=0,write('done'),!.
move(X,Y,Z):-X<4,\+member((4,Y),Z),write("fill 4 jug"),nl,move(4,Y,[(4,Y)|Z]).
move(X,Y,Z):-Y<3,\+member((X,3),Z),write("fill 3 jug"),nl,move(X,3,[(X,3)|z]).
move(X,Y,Z):-X>0,\+member((0,Y),Z),write("pour 4 jug"),nl,move(0,Y,[(0,Y)|Z]).
move(X,Y,Z):-Y>0,\+member((X,0),Z),write("pour 3 jug"),nl,move(X,0,[(X,0)|Z]).
move(X,Y,Z):-P is X+Y,P>=4,Y>0,K is 4-X,M is Y-K,\+member((4,M),Z),write("pour from
3jug to 4jug"),nl,move(4,M,[(4,M)|Z]).
move(X,Y,Z):-P is X+Y,P>=3,X>0,K is 3-Y,M is X-K,\+member((M,3),Z),write("pour from
4jug to 3jug"),nl,move(M,3,[(M,3)|Z]).
move(X,Y,Z):-K is X+Y,K<4,Y>0,\+member((K,0),Z),write("pour from 3jug to
4jug"),nl,move(K,0,[(K,0)|Z]).
move(X,Y,Z):-K is X+Y,K<3,X>0,\+member((0,K),Z),write("pour from 4jug to
3jug"),nl,move(0,K,[(0,K)|Z]).
OUTPUT:
?- move(0,0,[(0,0)])
fill 4 jug
fill 3 jug
pour 4 jug
pour 3 jug
fill 4 jug
pour from 4jug to 3jug
pour 3 jug
pour from 4jug to 3jug
fill 4 jug
pour from 4jug to 3jug
pour 3 jug
done
RESULT:
Thus the program to implement water jug problem using prolog was executed and the
output was verified successfully.