0% found this document useful (0 votes)
3 views2 pages

Labsheet4FAI

Uploaded by

vuppalashasank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Labsheet4FAI

Uploaded by

vuppalashasank
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Name:Vuppala Shasank

Roll No.: AM.SC.U4AIE23064

from collections import defaultdict

def water_jug_solver(jug1, jug2, aim):


visited = defaultdict(lambda: False)
operations_count = float('inf')

def solve(amt1, amt2, steps):


nonlocal operations_count

if visited[(amt1, amt2)]:
return False

visited[(amt1, amt2)] = True

if amt1 == aim or amt2 == aim:


if steps < operations_count:
operations_count = steps
print(f"Solution found: ({amt1}, {amt2}) in {steps}
steps")
return True

print(f"Current state: ({amt1}, {amt2}), Steps: {steps}")

if solve(jug1, amt2, steps + 1):


return True
if solve(amt1, jug2, steps + 1):
return True
if solve(0, amt2, steps + 1):
return True
if solve(amt1, 0, steps + 1):
return True

transfer = min(amt1, jug2 - amt2)


if solve(amt1 - transfer, amt2 + transfer, steps + 1):
return True

transfer = min(amt2, jug1 - amt1)


if solve(amt1 + transfer, amt2 - transfer, steps + 1):
return True

return False

if not solve(0, 0, 0):


print("No solution found.")
else:
print(f"Minimum operations to reach {aim} liters:
{operations_count}")

jug1, jug2, aim = 4, 3, 2


water_jug_solver(jug1, jug2, aim)

Current state: (0, 0), Steps: 0


Current state: (4, 0), Steps: 1
Current state: (4, 3), Steps: 2
Current state: (0, 3), Steps: 3
Current state: (3, 0), Steps: 4
Current state: (3, 3), Steps: 5
Solution found: (4, 2) in 6 steps
Minimum operations to reach 2 liters: 6

You might also like