Professional Documents
Culture Documents
Ai PRA3
Ai PRA3
def __hash__(self):
return hash((self.x, self.y))
while stack:
current_state, path = stack.pop()
visited.add(current_state)
next_states = []
# Fill jug x
if current_state.x < x:
new_x = x
new_y = current_state.y
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
# Fill jug y
if current_state.y < y:
new_x = current_state.x
new_y = y
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
# Empty jug x
if current_state.x > 0:
new_x = 0
new_y = current_state.y
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
# Empty jug y
if current_state.y > 0:
new_x = current_state.x
new_y = 0
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
# Pour from x to y
if current_state.x > 0 and current_state.y < y:
pour_amount = min(current_state.x, y - current_state.y)
new_x = current_state.x - pour_amount
new_y = current_state.y + pour_amount
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
# Pour from y to x
if current_state.y > 0 and current_state.x < x:
pour_amount = min(current_state.y, x - current_state.x)
new_x = current_state.x + pour_amount
new_y = current_state.y - pour_amount
new_state = JugState(new_x, new_y)
if new_state not in visited:
next_states.append((new_state, path + [current_state]))
stack.extend(next_states)
return None
if __name__ == "__main__":
x_capacity = 4 # Capacity of jug x
y_capacity = 3 # Capacity of jug y
target_amount = 2 # Desired amount to measure
if solution_path:
print(f"Solution found to measure {target_amount} liters:")
for state in solution_path:
print(f"Jug X: {state.x} liters, Jug Y: {state.y} liters")
else:
print("No solution found.")
Output: