Created
April 26, 2016 03:28
-
-
Save rtoal/aea3e02f50635ccdccc1ea5ac0d0ddcf to your computer and use it in GitHub Desktop.
The famous 10-7-4 water jug problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 10-7-4 Water Jug Problem | |
# Get 2 units of water in the 7-container or the 4-container | |
# Starting state is (0,7,4) | |
# Operations are F10, F7, F4, T107, T104, T710, T74, T410, T47 | |
# Goal states are (x,2,z) and (x,y,2) | |
operations = { | |
'F10' : lambda x, y, z: [10, y, z], | |
'F7' : lambda x, y, z: [x, 7, z], | |
'F4' : lambda x, y, z: [x, y, 4], | |
'T107' : lambda x, y, z: [0, y+x, z] if y+x<=7 else [x-(7-y), 7, z], | |
'T104' : lambda x, y, z: [0, y, z+x] if z+x<=4 else [x-(4-z), y, 4], | |
'T710' : lambda x, y, z: [x+y, 0, z] if x+y<=10 else [10, y-(10-x), z], | |
'T74' : lambda x, y, z: [x, 0, z+y] if z+y<=4 else [x, y-(4-z), 4], | |
'T410' : lambda x, y, z: [x+z, y, 0] if x+z<=10 else [10, y, z-(10-x)], | |
'T47' : lambda x, y, z: [x, y+z, 0] if y+z<=7 else [x, 7, z-(7-y)], | |
} | |
def dfs(state, visited, solution): | |
solution.append(state) | |
if state[1] == 2 or state[2] == 2: | |
return True | |
for (op, transition) in operations.items(): | |
next = transition(*state) | |
if str(next) not in visited and dfs(next, visited|{str(next)}, solution): | |
return True | |
solution.pop() | |
return False | |
solution = [] | |
if dfs([0,7,4], set(), solution): | |
print(solution) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment