Prolog algorithm for 3 water jugs

689 views Asked by At

I was trying to make a program to solve 3 any size water jugs problem. I have written this much

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).

With this code I am getting the result that I need. What other way could I solve this problem without dividing the first jug capacity, but by pouring first jug to any other one until I fill them and by doing so calculating the Goal witch is the necessary amount in first jug?

P.S. I hope you can understand my broken English, can't think straight today

0

There are 0 answers