Steps for Water jug problem
Steps for Water jug problem
1. Initialization:
jug1_capacity = 4
jug2_capacity = 3
goal_state = (2, 0) # The target water amounts in the jugs
start_state = (0, 0) # Both jugs are empty initially
2. is_valid Function:
Ensures that the amounts of water in the jugs are within their respective capacities.
def solve_water_jug_problem(start_state):
visited = set()
queue = deque([(start_state, [])]) # Queue stores (state, path to state)
while queue:
current_state, path = queue.popleft()
if current_state == goal_state:
return path + [current_state]
moves = [
(jug1_capacity, jug2_amount), # Fill Jug 1 to its capacity
(jug1_amount, jug2_capacity), # Fill Jug 2 to its capacity
(0, jug2_amount), # Empty Jug 1 completely
(jug1_amount, 0), # Empty Jug 2 completely
(max(0, jug1_amount - (jug2_capacity - jug2_amount)),
min(jug2_capacity, jug1_amount + jug2_amount)), # Pour Jug 1 into Jug 2
(min(jug1_capacity, jug1_amount + jug2_amount),
max(0, jug2_amount - (jug1_capacity - jug1_amount))) # Pour Jug 2 into Jug 1
]
Checks if the new state is valid and has not been visited.
Adds the new state and the updated path to the queue.
solution_path = solve_water_jug_problem(start_state)
if solution_path:
print("Solution found:")
for step in solution_path:
print(step)
else:
print("No solution exists!")
Prints the sequence of states leading to the goal state, or reports that no solution exists.
//// code for water jug problem
from collections import deque
jug1_capacity = 4
jug2_capacity = 3
goal_state = (2, 0)
start_state = (0, 0)
def solve_water_jug_problem(start_state):
visited = set()
queue = deque([(start_state, [])])
while queue:
current_state, path = queue.popleft()
if current_state == goal_state:
return path + [current_state]
return None
solution_path = solve_water_jug_problem(start_state)
if solution_path:
print("Solution found:")
for step in solution_path:
print(step)
else:
print("No solution exists!")