one-file-projects/wolfsheep.py

58 lines
1.8 KiB
Python
Raw Permalink 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:
2015-04-29 06:57:52 +02:00
invalid_states = [ set({Model.Wolf,Model.Sheep}), set({Model.Sheep, Model.Cabbage}) ]
2016-02-18 14:37:59 +01:00
all_entities = set([Model.Man, Model.Wolf, Model.Sheep, Model.Cabbage])
2015-04-29 06:57:52 +02:00
2015-04-28 23:16:52 +02:00
def simulate(self, state, stack=[]):
stack = stack + [state]
2016-02-18 14:37:59 +01:00
if state.right == Simulator.all_entities:
2015-04-28 23:16:52 +02:00
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]) ) )
2015-04-29 07:03:53 +02:00
nextStates = filter(
2015-04-29 06:57:52 +02:00
lambda s: not(
s in stack or
any([ any([ invalid_state <= m for invalid_state in Simulator.invalid_states ]) and Model.Man not in m for m in [s.left,s.right] ])
2015-04-28 23:16:52 +02:00
)
2015-04-29 07:03:53 +02:00
, nextStates) #Remove invalid and previous states.
2015-04-28 23:16:52 +02:00
for s in nextStates:
m = self.simulate(s,stack)
if m is not None:
return m
return None
if __name__ == "__main__":
sim = Simulator()
2016-02-18 14:37:59 +01:00
result = sim.simulate(Model(Simulator.all_entities,[]))
2015-04-28 23:16:52 +02:00
i = 0
for state in result:
print("%d: %s" % (i,state.pretty()))
i+=1