We have two water jugs, one measures 4 Gallons (4G) while the other measure 9 Gallons (9G). But there is no measuring label mentioned on either of these two jugs i.e. we cannot know the exact amount filled in the jug. Now, assuming there is an infinite amount of water supply, can we measure all 1G, 2G, 3G…….. upto 9G using these unmarked jugs.
Hint: We can empty the jugs, and transfer water from one jug to other.
Yes, we can measure all from 1G to 9G.
- 4G: Simply fill the 4G jug completely.
- 9G: Simply fill the 9G jug completely.
- 5G: Fill the 9G jug fully. Now transfer water from 9G to 4G till 4G gets full. Now 9G will have 5Gallons of water. Hence, measured 5G
- 1G: Fill the 9G jug to its maximum. Now transfer water from 9G to 4G till 4G gets full. Empty the 4G jug. Again transfer from 9G to 4G till 4G gets full. Now we are left with 1G in 9G jug.
- 8G: Fill up 4G and empty it into 9G. Again fill up 4G and empty it into 9G. Now 9G has 8 Gallons of water.
- 3G: Firstly, fill the 4G jug and empty it into 9G jug. Again fill 4G and empty it into 9G.
Again repeat the same procedure. So now 4G jug will have 3G amount of water and 9G will be full. Hence, measured 3G.
- 7G: Measure 3G as mentioned above. Now transfer this 3 Gallons of water from 4G to 9G. And now completely fill 4G jug. Now we have 4 Gallons in 4G jug and 3 Gallons in 9G jug. Hence, measured 7G.
- 2G: As mentioned above, firstly measure up to 7G. The scenario is that 4G jug is full and 9G jug has 3G water. Transfer the water from 4G to 9G so that 4G becomes empty and 9G measures 7G. Now completely fill 4G and then start transferring water to 9G till 9G becomes full. Now we will be left with only 2G in 4G jug. Hence, measured 2G
- 6G: Repeat the same procedure till measuring 2G as stated above. Now empty the 9G jug and transfer 2G from 4G jug to 9G jug. And now fill up the 4G jug completely. Hence, we have 4 Gallons in 4G jug and 2 Gallons in 9G jug. Thus measuring 6G.
This article is contributed by Arushi Dhamija. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.