Title: Water and Jug Problem Source: leetcode.com
You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available.
You need to determine whether it is possible to measure exactly z litres using these two jugs.
If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.
Operations allowed:
- Fill any of the jugs completely with water.
- Empty any of the jugs.
- Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.
Example 1: (From the famous “Die Hard” example)
1 2 |
Input: x = 3, y = 5, z = 4 Output: True |
Example 2:
1 2 |
Input: x = 2, y = 6, z = 5 Output: False |
Python solution
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 |
''' https://leetcode.com/problems/water-and-jug-problem/ ''' ''' The idea is to get the GCD of given Jugs' capacity and if mod of required value from GCD is 0 then we could obtain that required value from given Jugs. ''' class Solution(object): def getGCD(self, x, y): while x != y: if x > y: x = x - y else: y = y - x return x def canMeasureWater(self, x, y, z): """ :type x: int :type y: int :type z: int :rtype: bool """ if z <= 0: return True if x <= 0 or y <= 0: return x + y == z if z > x + y: return False gcd = self.getGCD(x,y) if gcd == 1: return True elif z % gcd == 0: return True return False |