Initial state: (0, 0) means both jugs are empty.
% Goal state: (2, _), where the first jug has exactly 2 liters of water.
% The capacity of the jugs
capacity(4, 3).
% Define possible actions: fill, empty, pour from one jug to another.
% Fill the 4-liter jug
action((X, Y), (4, Y)) :-
capacity(4, _),
X < 4.
% Fill the 3-liter jug
action((X, Y), (X, 3)) :-
capacity(_, 3),
Y < 3.
% Empty the 4-liter jug
action((X, Y), (0, Y)) :-
X > 0.
% Empty the 3-liter jug
action((X, Y), (X, 0)) :-
Y > 0.
% Pour water from the 4-liter jug into the 3-liter jug
action((X, Y), (NewX, NewY)) :-
capacity(_, MaxY),
X > 0,
Y < MaxY,
Transfer is min(X, MaxY - Y),
NewX is X - Transfer,
NewY is Y + Transfer.
% Pour water from the 3-liter jug into the 4-liter jug
action((X, Y), (NewX, NewY)) :-
capacity(MaxX, _),
Y > 0,
X < MaxX,
Transfer is min(Y, MaxX - X),
NewY is Y - Transfer,
NewX is X + Transfer.
% Define the search predicate to reach the goal state (2, _)
solve(Path) :-
search((0, 0), [(0, 0)], Path).
% Recursive search to find the solution path
search((2, _), Visited, Path) :-
reverse(Visited, Path).
search(State, Visited, Path) :-
action(State, NextState),
\+ member(NextState, Visited), % Avoid revisiting states
search(NextState, [NextState | Visited], Path).
Comments
Post a Comment