Created
December 11, 2016 22:52
-
-
Save stringertheory/05e76b862e424afa36a8bd9dead2e641 to your computer and use it in GitHub Desktop.
Playing around with the Prisoner Hat Riddle (http://bit.ly/2hmNSav)
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
"""Playing around with the Prisoner Hat Riddle (http://bit.ly/2hmNSav) | |
""" | |
import random | |
def make_hats(n_people): | |
"""Return a list of random black or white hats.""" | |
return [random.randint(0, 1) for _ in range(n_people)] | |
def count_blacks(hats): | |
"""Return a list of the number of black hats each person can see.""" | |
# person at end of line can't see any black hats | |
blacks_count = 0 | |
blacks = [] | |
for hat in reversed(hats): | |
blacks.append(blacks_count) | |
blacks_count += hat | |
blacks.reverse() | |
return blacks | |
def make_guesses(blacks): | |
"""Make the aliens happy.""" | |
guesses = [] | |
remaining_parity = None | |
for index, count in enumerate(blacks): | |
parity = count % 2 | |
# back of line uses parity as guess | |
if not index: | |
guess = parity | |
remaining_parity = parity | |
# if previous guess was | |
else: | |
if remaining_parity == parity: | |
guess = 0 | |
else: | |
guess = 1 | |
remaining_parity = int(not remaining_parity) | |
guesses.append(guess) | |
return guesses | |
def circle(value): | |
"""Format the hat for printing in terminal.""" | |
if value: | |
return u"\u25CF" | |
else: | |
return u"\u25CB" | |
def simulate(n_people): | |
"""Do one run of the "Prisoner Hat Riddle" (http://bit.ly/2hmNSav)""" | |
hats = make_hats(n_people) | |
blacks = count_blacks(hats) | |
guesses = make_guesses(blacks) | |
print ''.join(circle(_) for _ in hats) | |
print ''.join(circle(_) for _ in guesses) | |
print '' | |
if __name__ == '__main__': | |
for i in range(10): | |
simulate(79) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment