Home » Water Jug Problem in Java

Water Jug Problem in Java

by Online Tutorials Library

Water Jug Problem in Java

Water Jug Problem is one of the most important problems to solve in Java. The water jug problem is a problem where we have two jugs, “i” liter jug and “j” liter jug (0 < i < j). Both jugs will initially be empty, and they don’t have marking to measure small quantities. Now, we need to measure d liters of water by using these two jugs where d < j. We use the following three operations to measure small quantities by using the two jars:

  1. Empty a Jug.
  2. Fill a Jug
  3. We pour the water of one jug into another one until one of them is either full or empty.

In Java, we implement the logic for getting the minimum number of operations required to measure the d liter quantity of water.

There are various ways to solve water jug problems in Java, including GCD, BFS, and DP. In this section, we implement the logic for solving the Water Jug problem by using GCD.

WaterJugProblemExample.java

Output:

Water Jug Problem in Java

We can use one more approach for solving Water Jug problem whose code implementation is given below:

WaterJugProblemExample1.java

Output:

Water Jug Problem in Java


You may also like