StyleInCode

RSS

 

Wolf, Goat and Cabbage Problem

27 February 2025

A solution for the Wolf, Goat and Cabbage Problem.

Solution

""" wolf_goat_cabbage.py """

# usage: python3 wolf_goat_cabbage.py

left = {'cabbage', 'goat', 'wolf'}
right = set()

rules = {frozenset(['cabbage', 'goat']), frozenset(['goat', 'wolf'])}
person = 'Harald'

print(left | {person}, set(), right)

while left:
    obj = left.pop()
    while left in rules:
        left.add(obj)
        obj = left.pop()

    print(left, {obj, person}, right)

    right.add(obj)

    if right in rules:
        obj = (right - {obj}).pop()
        right.remove(obj)
        print(left, {obj, person}, right)
        left.add(obj)
    else:
        print(left, set(), right | {person})

Categories

Links