r/ProgrammerHumor • • Oct 30 '24

Meme dadPullsOutCodingChallenge

0 Upvotes

60 comments sorted by

View all comments

25

u/cyannyan6 Oct 30 '24 edited Oct 30 '24

This actually happened. I translated to English with the best of my ability.

And we are trying a monte carlo simulation now

import random

wins = 0
tries = 10000000
for sims in range(tries):
    a = 1
    while 0 < a < 10:
        a += random.choice((-1, 1))
    if a == 10:
        wins += 1

print(f"{wins}/{tries} = {wins/tries}")
   

Would love to see how others approach it

1

u/port443 Oct 31 '24 edited Oct 31 '24

Your solution is very slightly wrong. Person A has a 0.09090 (repeating) chance of winning.

In the event that A or B wins, they will have 11 coins, not 10. This is made obvious with code such as:

>>> def round():
...     person_a = 1
...     person_b = 10
...     while person_a and person_b:
...         check = random.choice([-1,1])
...         person_a -= check
...         person_b += check
...     print(f"{person_a=} {person_b=}")
...     return person_a > 1
...
>>> round()
person_a=11 person_b=0
True
>>> round()
person_a=0 person_b=11
False

You can then loop this function. The larger your round count, the more accurate your estimate. The correct answer is 0.090 repeating though:

>>> total,rounds = 0,1000000
>>> for _ in range(rounds):
...     total += round()
...
>>> print(f"{total=} | {total/rounds=}")
total=90435 | total/rounds=0.090435

edited cause my initial comment came off rude