Skip to content

Instantly share code, notes, and snippets.

@a-tal
Last active August 29, 2015 14:12
Show Gist options
  • Save a-tal/830f1f3da5273551f65a to your computer and use it in GitHub Desktop.
Save a-tal/830f1f3da5273551f65a to your computer and use it in GitHub Desktop.
strategy X
"""python proof for: https://www.youtube.com/watch?v=eivGlBKlK6M
100 boxes randomly containing numbers 1-100.
50 choices per player.
100 players numbered 1-100.
all players must find their number in a box to win.
random selection strategy vs strategy X (use -x on the cmd line to enable)
"""
import sys
import random
class Game(object):
"""A complete playthrough of 100 players playing the game."""
def __init__(self, strat_x=False, players=100):
numbers = list(range(1, players + 1))
random.shuffle(numbers)
self.boxes = {
box: num for box, num in zip(range(1, players + 1), numbers)
}
self.strategy = self.strat_x if strat_x else self.random_strat
self.players = players
self.selections = None
self.wins = 0
def strat_x(self, player, previous):
"""Perform strategy X for a player.
Args::
player: the player's number
previous: the previous result selected by this player, or None
"""
return self.select(player if previous is None else previous)
def random_strat(self, player, previous):
"""Use random selection for all players."""
return self.select(random.choice(list(
set(range(1, self.players + 1)) - set(self.selections)
)))
def select(self, box):
"""Returns the number inside of the box and tracks the selection."""
self.selections.append(box)
return self.boxes[box]
def play(self):
"""Plays the game for self.players using self.strategy."""
for player in range(1, self.players + 1):
self.selections = [] # reset this players choices
choice = None
while len(self.selections) <= 50:
choice = self.strategy(player, choice)
if choice == player:
self.wins += 1
break
if self.wins == self.players:
# print("all players have won the game")
return 1
else:
# print("some players lost the game :/ {} wins/{} players".format(
# self.wins, self.players
# ))
return 0
if __name__ == "__main__":
WINS = 0
GAMES = 1000
STRAT_X = "-x" in sys.argv
for _ in range(GAMES):
WINS += Game(STRAT_X).play()
print("TOTAL WINS: {}/{} = {:.2f}%".format(
WINS, GAMES, (WINS / GAMES) * 100
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment