What's wrong with my prolog program for solving the 3 jugs of water puzzle?

前端 未结 3 1748
忘了有多久
忘了有多久 2021-01-23 03:29

Can anyone find why I can\'t have any true answers with my \'go\' at this code? For example, I write go(7,3,l) and I suppose that it should move 3 litres of water t

3条回答
  •  心在旅途
    2021-01-23 04:26

    Well so as I said in my comment, I kinda wouldn't know how to help you with your current work since there are so many wrong things in it. I'd advise you to read a nice tutorial about Prolog (such as Learn Prolog now) so that you can grab the language basics. Here is a simple way to solve your problem if you're interested. If you don't want your problem to be spoiled, just don't read further : ] (the one I posted is about a 3/5/8 jugs and a 4/4 split).

    go(Path) :-
        solve([0-3, 0-5, 8-8], [], [], Temp),
        reverse(Temp, Path).
    
    solve(State, _Visited, Path, Path) :-
        equivalent(State, [0-3, 4-5, 4-8]).
    solve(State, Visited, Acc, Path) :-
        move(State, NewState),
        NewState = [_-From, _-To|_],
        forall(member(Past, Visited), \+ equivalent(Past, NewState)),
        solve(NewState, [NewState|Visited], [From-To|Acc], Path).
    
    equivalent(State1, State2) :-
        forall(member(X, State1), member(X, State2)).
    
    move(State, [NewX-From, NewY-To|NewRest]) :-
        select(X-From, State, Rest),
        X \== 0,
        select(Y-To, Rest, NewRest),
        Fillable is To - Y,
        ToFill is min(X, Fillable),
        NewY is Y + ToFill,
        NewX is X - ToFill.
    

    If you need explanations about the code once you've read a little more about prolog, don't hesitate!

提交回复
热议问题