Consider the following problem: 1. You have a four-gallon jug and a three-gallon jug, neither of which has any markings. Understand what this means. The only reliable observations are: a jug is empty in which case it has zero gallons in it; or, a jug is full, in which case it has its "capacity" gallons in it, and any other conclusions you can logically draw from these states. For example, say you fill the 4-gallon jug, and then fill the 3-gallon jug from it, you can logically conclude that there is 1 gallon left in the 4-gallon jug. Since the jugs have no markings, no other amounts can be transferred from the full 4- gallon jug to the 3-gallon jug. In this example, you cannot transfer 1, or 1.5, or 2, or 2.25, or 3.142 gallons of water from the 4- gallon jug to the 3-gallon jug. 2. There is a faucet from which you can top off the jugs as many times as you wish. Following this, a jug has its "capacity" gallons in it. 3. You can empty one jug into the other, or onto the ground, in which case the jug is known to have zero gallons in it. 4. You can transfer water between the two jugs. Again, since the jugs have no markings, the only transfers that are logical are those that leave one jug full or the other empty. Write a Prolog program that finds a sequence of moves (in the form of a list of instructions) that, starting from two empty jugs, ends with exactly two gallons of water in the 4-gallon jug and no water in the 3-gallon jug.
/*
*
* [a,b] - represents a problem state with a gallons in the 4-gallon jug
* and b gallons in the 3-gallon jug
*/
%% You can fill the 4 gallon jug from the faucet, taking you from a
%% problem state [X,Y] to a problem state [4,Y],
%% provided X < 4.
move([X,Y],'Top off 4-gallon jug from faucet',[4,Y]) :- X<4.
%%
%
%2. Rule corresponding to the move 'Top off 3-gallon jug from faucet'
move([X,Y],'Top off 3-gallon jug from faucet',[X,3]) :- Y<3.
%
%
%3. Rule corresponding to the move 'Empty 4-gallon jug onto the ground'
%
%
%4. Rule corresponding to the move 'Empty 3-gallon jug onto the ground'
%
% 5. Rule corresponding to the move 'Top off 4-gallon jug from 3-gallon
% jug'
%
% 6. Rule corresponding to the move 'Top off 3-gallon jug from 4-gallon
% jug'
%
%7. Rule corresponding to the move 'Empty 3-gallon jug into 4-gallon jug'
%
%8. Rule corresponding to the move 'Empty 4-gallon jug into 3-gallon jug'
%
%
%%solution predicates
% To solve the problem try this: length(X, Y), Y < 10, solution([0,0], X).
%
% [2,0] is the goal state. No move required if you are in this state
solution([2,0],[]).
%
%The list of moves [Move|Rest] constitutes a solution from PresentState
%if Move takes you from PresentState to NextState
%and Rest represents a sequence of moves that will take
%you from NextState to the goal state.
solution(PresentState,[Move|Rest]) :- move(PresentState,Move,NextState),
solution(NextState,Rest).
Step by step
Solved in 2 steps