1

I'm solving the water jug problem using state space and dfs,jug 1 have capacity of 4,jug 2 have capacity of 3,show the path to make jug 2 have 2 in it

% Water Jug problem using DFS in Prolog

% Define the initial state
start(jug(0,0)).

% Define the goal state
goal(jug(_,2)).

% Define the actions that can be taken
action(fill1, jug(_,Y), jug(4,Y)).
action(fill2, jug(X,_), jug(X,3)).
action(empty1, jug(_,Y), jug(0,Y)).
action(empty2, jug(X,_), jug(X,0)).
action(pour1to2, jug(X,Y), jug(X1,Y1)) :- X > 0, Y < 3, X1 is 0, Y1 is min(3, X + Y).
action(pour2to1, jug(X,Y), jug(X1,Y1)) :- Y > 0, X < 4, Y1 is 0, X1 is min(4, X + Y).

% Define the DFS algorithm
dfs(State, [], _) :- goal(State).

dfs(State, [Action|Actions], Visited) :-
    action(Action, State, State1),
    State1 \= State,
    \+ member(State1, Visited),
    dfs(State1, Actions, [State1|Visited]).`

To run the program
start(State), dfs(State, Actions, [State]).

I have tried to print what inside

fill1
fill2
empty1
fill1
empty2
pour2to1
fill1
fill2
fill1
empty1
empty2
pour2to1
empty1
pour1to2
empty2
empty1

... but it make no sense,The program always return false. Could anyone help me to find what is wrong with it?

5
  • Adding writeln(State1), as the penultimate line, would help with debugging. It works when goal is changed from 2 to 3. Is there definitely a solution for 2?
    – brebs
    Mar 29 at 6:55
  • it still loop endlessly,i can't figure through the output
    – Ni No
    Mar 29 at 7:26
  • (0,0) -> (4,0)->(4,3) ->(0.3) ->(3,0) -> (3,3)->(4,2) -> (0,2) here is the answer for 2 when i do hand write
    – Ni No
    Mar 29 at 7:28
  • What operation would go from 3,3 to 4,2? Note that _,2 would unify with 4,2.
    – brebs
    Mar 29 at 9:00
  • it work, return [fill1, fill2, empty1, pour2to1, fill2, pour2to1 lead to (4,2) after i change to pour1to2 and pour2to1 'is 0' part.thank you very much
    – Ni No
    Mar 29 at 10:08

1 Answer 1

1

change the action pour2to1 and pour1to 2 to

action(pour1to2, jug(X,Y), jug(X1,Y1)) :-
X > 0, Y < 3, Y1 is X + Y, X1 is max(0, Y1 - 3). 
action(pour2to1, jug(X,Y), jug(X1,Y1)) :- 
Y > 0, X < 4, X1 is X + Y, Y1 is max(0, X1 - 4).

because the old code have wrong logic, X1 or Y1 always 0 when pouring to another

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.