3个水壶的Prolog算法

时间:2016-12-19 16:46:52

标签: prolog water-jug-problem

我正在尝试制作一个程序来解决3个任何大小的水壶问题。我写了这么多

refil(Size,_,_,Size).
refil(FirstSize,SecondSize,ThirdSize,Goal):-
    move(FirstSize,SecondSize,ThirdSize,FirstSize,0,0,Goal). 
move(_,_,_,Goal,_,_,Goal).
move(FirstSize,SecondSize,ThirdSize,New1,New2,New3,Goal):-
    (
            reduce(New1,TempVal1,-(New2-SecondSize),Goal)-> NextVal1 is Goal, NextVal2 is TempVal1,NextVal3 is New3, write('From 1st to 2nd'),nl;
            reduce(New1,TempVal1,-(New3-ThirdSize),Goal)-> NextVal1 is Goal,NextVal3 is TempVal1,NextVal2 is New2, write('From 1st to 3nd'),nl;
            reduce1(New1,NextVal1,-(New2-SecondSize))-> NextVal2 is New2 - (New2-SecondSize),NextVal3 is New3, write('From 1st to 2nd'),nl;
            reduce1(New1,NextVal1,-(New3-ThirdSize))-> NextVal3 is New3 - (New3-ThirdSize), NextVal2 is New2, write('From 1st to 3rd'),nl;
            reduce1(New2,NextVal2,-(New3-ThirdSize))-> NextVal3 is 0, NextVal1 is New1, write('From 2nd to 3rd'),nl;
            reduce1(New3,NextVal3,-(New2-SecondSize))-> NextVal2 is 0, NextVal1 is New1, write('From 3rd to 2nd'),nl;
            reduce2(New1, NextVal1, New2, SecondSize)-> NextVal2 is 0, NextVal3 is New3, write('From 2nd to 1st'),nl;
            reduce2(New1, NextVal1, New3, ThirdSize)-> NextVal3 is 0, NextVal2 is New2, write('From 3rd to 1st'),nl
    ),
    write('1st Jug: '), write(NextVal1),nl,
    write('2nd Jug: '), write(NextVal2),nl,
    write('3rd Jug: '), write(NextVal3),nl,
    move(FirstSize,SecondSize,ThirdSize,NextVal1,NextVal2,NextVal3,Goal).

reduce(D,Dn,Size,Goal):-
not(D mod 2 is 0),
X is D - Goal,
X > 0,
X < Size,
Dn is X.

reduce1(D, Dn, Size):-
X is Size, not(X is 0),
D - Size >= 0,
Dn is D - Size.

reduce2(D, Dn, Size, Jug):-
X is Size,
Jug - D >= X,
reduce1(D, Dn, Size).

使用此代码,我得到了我需要的结果。如果没有划分第一个水壶的容量,我可以用其他方式解决这个问题,但是先将水壶倒在任何其他水壶上,直到我填满它们,这样做计算目标女巫是第一个水壶的必要数量?

P.S。我希望你能理解我破碎的英语,今天不能直接思考

0 个答案:

没有答案