Is there a general solution to the water-bucket logic problem?

15.2k Views Asked by At

Having an infinite supply of water and two containers, one for 3 liters and one for 5 liters, how would you measure 4 liters?

Each step in the solution can be one of three things: Fill up a container all of the way, empty a container completely, or use one container to fill up another as much as possible.

The solution to the original problem is: Fill the 5 litre bucket (completely). The buckets are now 5/5 and 0/3. Pour the 5 litre bucket into the 3 litre one. They are now 2/5 and 3/3. Empty the 3 litre bucket. They are now 2/5 and 0/3. Pour the 5 litre bucket into the 3 litre one. They are now 0/5 and ⅔. Fill the 5 litre bucket. They are now 5/5 and ⅔. Pour the 5 litre bucket into the 3 litre one. They are now 4/5 and 3/3. Now, you have one bucket with the required amount of 4 litres.

Is there a standard algoritm to determine a possible solution, or even the shortest solution?

1

There are 1 best solutions below

3
On BEST ANSWER

You can look How not to Die Hard with Math or Lecture 7.5 - Case Study: the Water Pouring Problem (31:45) and, for example, corresponding GithubGist [Scala: water pouring problem solution]gist.github.com /hanbzu /7302266 "concise & clear code"