Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created January 27, 2019 03:13
Show Gist options
  • Save dengjonathan/b8c1fdb210d6444700a1f5a4f79aca21 to your computer and use it in GitHub Desktop.
Save dengjonathan/b8c1fdb210d6444700a1f5a4f79aca21 to your computer and use it in GitHub Desktop.
Python program simulating drawing marbles from a bag
import random
def takeMarble(isRed, bag):
color = 'red' if isRed else 'blue'
if isRed:
return ((bag[0] - 1, bag[1]), color)
else:
return ((bag[0], bag[1] - 1), color)
def pickMarble(bag):
count = bag[0] + bag[1]
if bag[0] == 0:
return takeMarble(False, bag)
if bag[1] == 0:
return takeMarble(True, bag)
pick = random.randint(0, count)
if pick < bag[0]:
return takeMarble(True, bag)
else:
return takeMarble(False, bag)
def putMarble(isRed, bag):
if isRed:
return (bag[0] + 1, bag[1])
else:
return (bag[0], bag[1] + 1)
def pick2MarblesAndReplace(bag):
# 1st iteration
(intBag, color1) = pickMarble(bag)
# 2nd iteration
(lastBag, color2) = pickMarble(intBag)
isRed = False if color1 == color2 else True
return putMarble(isRed, lastBag)
def whatIsLast():
# (red count, blue count)
bag = (101, 100)
while (bag[0] + bag[1]) > 1:
bag = pick2MarblesAndReplace(bag)
print(bag[0], bag[1])
if bag[0] > bag[1]:
return 'red'
else:
return 'blue'
answers = [whatIsLast() for i in range(100)]
for answer in answers:
print(answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment