OneCompiler

water jug problem

131

def waterJug(jugA, jugB, goal):
stack = []
visited = set()
stack.append((0, 0))

while stack:
    current_state = stack.pop()
    x, y = current_state
    print("Current state:", x, y)

    if (x == goal and y == 0) or (y == goal and x == 0):
        print("Last state:", x, y)
        return True

    if current_state in visited:
        continue

    visited.add(current_state)
    states = set()

    # Fill either jug
    states.add((jugA, y))
    states.add((x, jugB))

    # Empty either jug
    states.add((0, y))
    states.add((x, 0))

    # Pour water from one jug to another
    pour_AtoB = min(x, jugB - y)
    states.add((x - pour_AtoB, y + pour_AtoB))

    pour_BtoA = min(y, jugA - x)
    states.add((x + pour_BtoA, y - pour_BtoA))

    for state in states:
        if state not in visited:
            stack.append(state)

return False

Main code with user input

try:
jugA = int(input("Enter capacity of Jug A: "))
jugB = int(input("Enter capacity of Jug B: "))
goal = int(input("Enter the goal amount of water: "))

if waterJug(jugA, jugB, goal):
    print("Solution found")
else:
    print("Solution not found")

except ValueError:
print("Please enter valid integers for jug capacities and goal.")