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

前端 未结 3 1740
忘了有多久
忘了有多久 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:15

    The first thing you need to correct it's basic syntax: variables must begin with uppercase, so for instance you must change this rule

    pour(state(D1,D2,D3,n,l),move(D,C,r),state(D,C,D3,n,r)) :-
        D is D1-n,
        C is D2+n.
    

    to

    pour(state(D1,D2,D3,N,l),move(D,C,r),state(D,C,D3,N,r)) :-
        D is D1-N,
        C is D2+N.
    

    and

    newstate(state(D1,D2,D3,n,l),state(D11,D22,D33,n1,r)):-
            carry(M,C),
            M=<7,C=<3,
            D22 is D2+n,
            D11 is D1-n,
        D3 is D33,
        n1 is n,
            D2=<7,D1=<10,
        legal(D1,D2,D3).
    

    to

    newstate(state(D1,D2,D3,N,l),state(D11,D22,D33,N1,r)):-
        carry(M,C),
        M=<7,C=<3,
        D22 is D2+N,
        D11 is D1-N,
        D3 is D33,
        N1 is N,
        D2=<7,D1=<10,
        legal(D1,D2,D3).
    

    You should realize that N1 is valorized just in the first newstate/2 procedure: then correct the other instances of that rule.

    Then you should remove the useless dynamic assertions: think about your actual assert/retractall usage: what you need is to change the state moving 'water' between 'jugs' at any step: so you should assert/retract state/5 while looping in go, from an initial state (assert this at start program), to a final acceptable state, to be tested in go to stop the cycle.

    But this style based on state change leads to very difficult debugging. Try instead to remove altogheter the dynamic,assert/retractall, and pass around the state in your cycle.

提交回复
热议问题