I have been practicing recursion lately and I came up with this code to solve the water jug problem, given two jugs of volume jug1
and jug2
, where jug1 < jug2
, obtain a volume t
, where t < jug2
.
The algorithm below basically always pours from the smaller jug into the bigger jug, how would you improve the solution ?
I think I get the minimum number of steps this way... am I correct ?
jug1 = 5
jug2 = 7
t = 4
def jugSolver(amt1, amt2):
print(amt1, amt2)
if (amt1 == t and amt2 == 0) or (amt1 == 0 and amt2 == t):
return
elif amt2 == jug2:
jugSolver(amt1, 0)
elif amt1 != 0:
if amt1 <= jug2-amt2:
jugSolver(0, amt1+amt2)
elif amt1 > jug2-amt2:
jugSolver(amt1-(jug2-amt2),amt2+(jug2-amt2))
else:
jugSolver(jug1, amt2)
jugSolver(0,0)