Skip to content

Instantly share code, notes, and snippets.

@samueleverett01
Created September 9, 2017 21:19
Show Gist options
  • Save samueleverett01/2fda41b58db3e58a14ea6fec885b2af5 to your computer and use it in GitHub Desktop.
Save samueleverett01/2fda41b58db3e58a14ea6fec885b2af5 to your computer and use it in GitHub Desktop.
Monte Carlo simulation that calculates probability of winning a die-rolling game. Start with 1 chip, roll a 1, 2, 3, and you lose a chip, roll a 4 or 5, you gain a chip, roll a 6, you gain 2 chips. If you have no chips you lose, 4+ chips you win.
from random import choice
from tqdm import tqdm
trials = 10000000 # number of times the game is played (10,000,000)
lose = 0
win = 0
for game in tqdm(range(1, trials)):
options = [1, 2, 3, 4, 5, 6] # can roll any of these numbers
chips = 1 # starting point for each game
# continue this loop for as long as you haven't lost or won
while chips > 0 and chips < 4:
# picking random number out of options, like rolling a die
roll = choice(options)
if roll == 1 or roll == 2 or roll == 3:
chips -= 1
elif roll == 4 or roll == 5:
chips += 1
elif roll == 6:
chips += 2
if chips <= 0:
lose += 1
elif chips >= 4:
win += 1
print(win / lose)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment