Die Hard 3 Jugs Problem
Die Hard 3 Jugs Problem with Python
Write a Python program that simulates the process of obtaining exactly 4 liters of water using two buckets. The first bucket can hold 3 liters (m), and the second bucket can hold 5 liters (n). You have the following actions available: fill a bucket until it is full, empty a bucket completely, or transfer water from one bucket to the other until the target bucket is full.
Your program should iterate through the actions and keep track of the contents of each bucket (m and n) at each step. The program should continue until exactly 4 liters of water are obtained. Finally, output a list of pairs representing the contents of the buckets m and n at each step.
Expected ouput
(0, 0) (3, 0) (3, 5) (0, 5) (3, 2) (0, 2) (2, 0) (2, 5) (3, 4)
Solutions
# Step 1: Initialize Buckets
m_capacity = 3
n_capacity = 5
m_content = 0
n_content = 0
# Step 2: Define Actions
actions = [
lambda x, y: (m_capacity, y), # Fill m
lambda x, y: (0, y), # Empty m
lambda x, y: (x, n_capacity), # Fill n
lambda x, y: (x, 0), # Empty n,
lambda x, y: (0, x + y) if x + y <= n_capacity else (x - (n_capacity - y), n_capacity), # Pour m to n
lambda x, y: (x + y, 0) if x + y <= m_capacity else (m_capacity, y - (m_capacity - x)) # Pour n to m
]
# Step 3: Implement Simulation
steps = [(m_content, n_content)]
while True:
if n_content == 4:
break
for action in actions:
new_m_content, new_n_content = action(m_content, n_content)
if (new_m_content, new_n_content) not in steps:
m_content, n_content = new_m_content, new_n_content
steps.append((m_content, n_content))
# Step 4: Display Result
for step in steps:
print(step)
See here for more Python practice.
