
# leadSizes.py

'''
Contrary to popular notions, it is quite likely that in a long coin-tossing game one of the players remains practically the whole time on the winning side, the other on the losing side.

One should expect naively that in a game that lasts twice as long, Peter should lead about twice as often. This intuitive reasoning is false. The number of changes of lead in n trials increases only as \sqrt{n}
'''

import random
from frange import *
import matplotlib.pyplot as plt


def countPosNeg(n):
  hDiff = 0   # no of heads > no of tails
  posCount = 0    # no. of times diff is +ve
  negCount = 0    # no. of times diff is -ve
  numChgs = 0
  for j in range(n):
    flip = random.choice(['H', 'T'])
    if flip == 'H':
      hDiff += 1
    else:
      hDiff -= 1 
    if hDiff > 0:
      posCount += 1
    elif hDiff == 0:
      numChgs += 1
    else:
      negCount += 1

  return posCount/n, negCount/n, numChgs

ps = []
ns = []
chgs = []
vals =  range(100, 40000, 100)
for i in vals:
  posFrac, negFrac, numChgs = countPosNeg(i)
  ps.append(posFrac)
  ns.append(negFrac)
  chgs.append(numChgs)
  # print(f"{i:6d} {posFrac:6.0%} {negFrac:6.0%} {numChgs:6d}")

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
fig.tight_layout(pad=2) 

axes[0].hist(ps, bins=50)
axes[0].set_xlabel('Frac.')
axes[0].set_ylabel('counts')
axes[0].set_title('Positives Frac. Counts')

axes[1].hist(ns, bins=50)
axes[1].set_xlabel('Frac.')
axes[1].set_title('Negatives Frac. Counts')

axes[2].plot(vals, chgs)
axes[2].set_xlabel('n')
axes[2].set_ylabel('changes')
axes[2].set_title('No. lead changes')

plt.show()