From d0881dabdf7042cb13ef91624e16d40dccce0deb Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Tue, 28 Apr 2015 23:16:52 +0200 Subject: [PATCH] Wolf Sheep Cabbage Simulator --- wolfsheep.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 wolfsheep.py diff --git a/wolfsheep.py b/wolfsheep.py new file mode 100644 index 0000000..8596e5c --- /dev/null +++ b/wolfsheep.py @@ -0,0 +1,56 @@ +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