Coin flip duel

This week's Riddler Express poses the following question: if you and your friend take turns flipping one coin until someone tallies 10 heads (who wins), what advantage does the first flipper have over their friend?

This can definitely be solved analytically, but I submitted a brute force solution coded in Julia. My paste got a shoutout the following week! 🎉 (ノ^o^)ノ🎉

First, just using rand(Bool) for a coin flip, simulate one player's needed flips to get N heads, in one duel:

function nflips(N::Integer)
  n = 0
  heads = 0
  while heads < N
    if rand(Bool)
      heads += 1
    end
    n += 1
  end
  n
end
Simulating coin flips for one player until they reach N heads.

Then, all we need is to compare the result of this to the same call for another player. The edge for the first player comes down to the fact that they win with the condition <=, and conversely the second player only wins with >.

function p1winpct(nheads::Integer, nsims::Integer)
  n = 0
  for i in 1:nsims
    if nflips(nheads) <= nflips(nheads)
      n += 1
    end
  end
  n/nsims
end
Simulates nsims duels where the target is nheads heads.

So, we can just run p1winpct for a large number of trials, and we should arrive at an approximation of player one's advantage.

@time p1winpct(10,100000000)
 
# Output:
# 32.703553 seconds (5 allocations: 176 bytes)
#0.53295481
For 100 million trials, player one wins ~53% of the time.

For the target of 10 heads, out of 100 million trials, player one wins 53.3% of the time. Note that this is a 6.6 percentage point advantage over their trailing duelist.