└── wjug.py /wjug.py: -------------------------------------------------------------------------------- 1 | import math 2 | from collections import deque 3 | a=int(input("Enter jug A Capacity:")) 4 | b=int(input("Enter jug B Capacity:")) 5 | ai=int(input("Initially water in jug A : ")) 6 | bi=int(input("Initially water in jug B : ")) 7 | af=int(input("Final state of jug A : ")) 8 | bf=int(input("Final state of jug B : ")) 9 | if a<=0 or b<=0: 10 | print("Jug capacities must be positive") 11 | exit(1) 12 | if ai<0 or bi<0 or af<0 or bf<0: 13 | print("Negative values are not allowed") 14 | exit(1) 15 | if ai==af and bi==bf: 16 | print(f"Inital state is already the final stateL: jug a{ai} and jug b{bi}") 17 | exit() 18 | def bfs_wjug(a, b, ai, bi, af, bf): 19 | visited=set() 20 | queue=deque([(ai,bi,[])]) 21 | while queue: 22 | curr_ai, curr_bi, operations=queue.popleft() 23 | if(curr_ai, curr_bi) in visited: 24 | continue 25 | visited.add((curr_ai,curr_bi)) 26 | if curr_ai==af and curr_bi == bf: 27 | for i, op in enumerate(operations): 28 | print(f"Step {i + 1}: {op}") 29 | print(f"Final state Reached : jug A = {curr_ai}, jug B={curr_bi}") 30 | return 31 | possible_operations=[(a, curr_bi,"Fill Jug A"), 32 | (curr_ai,b,"Fill jug B"), 33 | (0,curr_bi,"Empty jug A"), 34 | (curr_ai,0,"Empty jug B"), 35 | (curr_ai - min(curr_ai, b- curr_bi),curr_bi + min(curr_ai, b - curr_bi),"Pour form A to B"), 36 | (curr_ai + min(curr_bi, a- curr_ai),curr_bi - min(curr_bi, a - curr_ai),"Pour form B to A"), 37 | ] 38 | for next_ai, next_bi, op in possible_operations: 39 | if(next_ai, next_bi) not in visited: 40 | queue.append((next_ai, next_bi, operations + [op])) 41 | print("No Solution found") 42 | return 43 | gcd = math.gcd(a,b) 44 | if(af<=a and bf<=b) and (af % gcd == bf % gcd == 0): 45 | bfs_wjug(a, b, ai, bi, af, bf,) 46 | else: 47 | print("the final state i snot achivable with the given capacities") 48 | 49 | 50 | 51 | 52 | 53 | --------------------------------------------------------------------------------