Created
June 10, 2011 15:35
-
-
Save chandlerprall/1019066 to your computer and use it in GitHub Desktop.
Python solver for bridge/zombie puzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
class State(object): | |
solutions = [] | |
def __init__(self): | |
self.zombied = [] | |
self.bridged = [] | |
self.flashlight = 'zombied' | |
self.weight = 0 | |
self.states = [] | |
self.actions = [] | |
self.person_1_index = 0 | |
self.person_2_index = 0 | |
def execute(self): | |
self.states.append(self) | |
# Are we donnneee?? | |
if len(self.zombied) == 0: | |
State.solutions.append(self) | |
return True | |
# loop through the people with the flashlight, try all combinations | |
if self.flashlight == 'zombied': | |
# We're on the zombie side | |
person_range = range(len(self.zombied)) | |
for index_1 in person_range: | |
for index_2 in person_range: | |
if index_1 != index_2: | |
new_state = copy.deepcopy(self) | |
new_state.flashlight = 'bridged' | |
person_1 = new_state.zombied[index_1] | |
person_2 = new_state.zombied[index_2] | |
new_state.zombied.remove(person_1) | |
new_state.zombied.remove(person_2) | |
new_state.bridged.append(person_1) | |
new_state.bridged.append(person_2) | |
if person_1['weight'] > person_2['weight']: | |
new_state.weight = new_state.weight + person_1['weight'] | |
else: | |
new_state.weight = new_state.weight + person_2['weight'] | |
new_state.actions.append('-> %s %s' % (person_1['name'], person_2['name'])) | |
new_state.execute() | |
else: | |
# We're on the bridge side | |
person_range = range(len(self.bridged)) | |
for index_1 in person_range: | |
new_state = copy.deepcopy(self) | |
new_state.flashlight = 'zombied' | |
person_1 = new_state.bridged[index_1] | |
new_state.bridged.remove(person_1) | |
new_state.zombied.append(person_1) | |
new_state.weight = new_state.weight + person_1['weight'] | |
new_state.actions.append('<- %s' % (person_1['name'])) | |
new_state.execute() | |
problem = State(); | |
problem.zombied.append({'name':'dad', 'weight': 1}) | |
problem.zombied.append({'name':'mom', 'weight': 2}) | |
problem.zombied.append({'name':'kid', 'weight': 5}) | |
problem.zombied.append({'name':'baby', 'weight': 10}) | |
problem.execute() | |
quickest = None | |
for solution in problem.solutions: | |
if (quickest is None or solution.weight < quickest.weight) and len(solution.zombied) == 0: | |
quickest = solution | |
print '%s minutes' % quickest.weight | |
print '\n'.join(quickest.actions) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment