one-file-projects/wolfsheep.py

57 lines
1.9 KiB
Python
Raw Normal View History

2015-04-28 23:16:52 +02:00
class Model:
Man = "M"
Wolf = "W"
Sheep = "S"
Cabbage = "C"
def __init__(self, left, right):
self.left = set(left)
self.right = set(right)
def __eq__(self,other):
return other.left == self.left and other.right == self.right
def __repr__(self):
return "(%s,%s)" % ( repr(self.left), repr(self.right))
def pretty(self):
return ",".join(self.left) + " <-> " + ",".join(self.right)
class Simulator:
def simulate(self, state, stack=[]):
#stack.append(state)
stack = stack + [state]
if state.right == set([Model.Man,Model.Wolf,Model.Sheep,Model.Cabbage]):
return stack
nextStates = []
if Model.Man in state.left:
for obj in state.left:
nextStates.append( Model(state.left - set([Model.Man,obj]) , state.right | set([Model.Man,obj]) ) )
else:
for obj in state.right:
nextStates.append( Model(state.left | set([Model.Man, obj]) , state.right - set([Model.Man,obj]) ) )
nextStates = list(filter(
lambda s: s not in stack and not(
( (set([Model.Wolf,Model.Sheep]) <= s.left or set([Model.Sheep, Model.Cabbage]) <= s.left) and Model.Man not in s.left ) or
( (set([Model.Wolf,Model.Sheep]) <= s.right or set([Model.Sheep, Model.Cabbage]) <= s.right) and Model.Man not in s.right )
)
, nextStates)) #Remove invalid and previous states.
#print("%s: %s\nstack: %s" % (state,nextStates,stack))
for s in nextStates:
m = self.simulate(s,stack)
if m is not None:
return m
return None
if __name__ == "__main__":
sim = Simulator()
result = sim.simulate(Model([Model.Man, Model.Wolf, Model.Sheep, Model.Cabbage],[]))
i = 0
for state in result:
print("%d: %s" % (i,state.pretty()))
i+=1