Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 12:58 PM 12/1/2011
- # based on playing Portal2, trying to figure out the typical
- # number of tries to win 3 rock-paper-scissors in a row by
- # a Monte Carlo simulation.
- import random
- MAX_SIMULATION_RUNS = 1000
- WINS_REQUIRED = 3
- def Random(N):
- return random.randrange(N)
- handtype = ( 'R', 'P', 'S',)
- resulttype = ( '>', '=', '<',)
- # 0 - A wins, 1 - tie, 2 - B wins
- def calcresult(a,b):
- return ((b - a) + 4) % 3
- def buildresultstring(a,b):
- s = "%c" % handtype[a]
- s = s + "%c" % resulttype[calcresult(a,b)]
- s = s + "%c" % handtype[b]
- return s
- totalplaycount = 0
- gamelenhistory = []
- for simulation_run in range(MAX_SIMULATION_RUNS):
- print "Simulation number %u:" % simulation_run
- winner = 0
- playcount = 0
- while winner < WINS_REQUIRED:
- playcount +=1
- a = Random(3)
- b = Random(3)
- print buildresultstring(a,b),
- if calcresult(a,b) == 0:
- winner += 1
- else:
- winner = 0
- print "WIN in %u!" % playcount
- totalplaycount += playcount
- gamelenhistory.append(playcount)
- print "Average of %0.1f tries to win %u in a row." % (
- float(totalplaycount) / MAX_SIMULATION_RUNS,
- WINS_REQUIRED)
- gamelenhistory = sorted( gamelenhistory)
- print "Median is about %u tries." % ( gamelenhistory[
- len(gamelenhistory) >> 1])
Add Comment
Please, Sign In to add comment