3 Jug Problem - Python Code
I came across this image by a Facebook page (Curiosity), which asked a solution to the famous Water Jug problem, involving 3 jugs.

Problem: Given 3 jugs of capacites: 12, 8 and 5 litres. Our 12 L jug is completely filled. Using these 3 jugs split the water to obtain exactly 6 Litres.
So I thought of writing a code in python to obtain the solution to the problem, instead of doing hit and trial.
I used DFS to search through all the states of the jugs. At each state, we’ll have certain choices of emptying water from one jug into another. We’ll try each choice, calling our function for each state, and if we reach the goal state, we stop.
[Note that the given program could be made smaller/modular, but it is more understandable given this way. Also, DFS might not give an optimal (best path) solution. For that use BFS]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
and that’s pretty much it.
Leave in the comments if you have anything in mind.