# flip coin until 10 heads
# Program to compute the distribution of the number of coin flips
# required to get 10 heads.
# Demonstrates: the use of break and continue in while loops,
# having one loop inside another loop, and save results in a list.
# Each experiment is a loop that flips until it has 10 heads.
# The outer loop runs the experiment 100,000 times. 

from random import randrange

iterations = 0 # int; number of times the experiment has been run

counts = [0]*50  # list of int variables for counts
overflow = 0  # int; counts any time it takes more than 50 flips

# outer loop 
while iterations < 100000:

    # one run of the experiment
    heads = 0  # int; number of heads seen so far
    flips = 0  # int; number of flips done so far
    # inner loop
    while True:
        # once through this block is one coin flip
        coin = randrange(0,2)  # coin is either 0 or 1
        # zero == heads, 1 == tails
        flips = flips+1 # count the flip
        if coin == 0:
            heads = heads + 1
        else:
            continue
            # goes up to the top of the while look and starts next
            # iteration
        # when to exit the inner loop -
        # when you have counted 10 heads
        if heads == 10:
            break
            # stops the while loop, immediately
            
    # now save the result of the last experiment before moving
    # on to the next
    if flips < 50:
        # usually
        counts[flips] = counts[flips]+1
        # flips is the index into the list counts
    else:
        # very unlikely this will ever happen, but let's
        # be prepared
        overflow = overflow+1
    # done with one experiment; count it. 
    iterations = iterations+1

### Second loop to print out results 
##i = 0 # int; index variable to run through list in order
##while i<50: # the list has 50 elements
##    print("for",i,"count is",counts[i])
##    # print one out
##    i = i+1
### also print the overflow value, which is almost always zero. 
##print("overflow",overflow)

# write results of the 100,000 experiments to a .csv file
outFile = open("flipCounts.csv","w") # open a new file for writing

i = 0  # sentry variable for while, also index variable for counts
while i<50:
    # the write method appends a single string to the end of the file
    # note that this is a streaming process (beginning to end of file)
    # just line reading a file.
    # We'll write one line at a time, each ending with newline character
    outFile.write(str(i)+", "+str(counts[i])+"\n")
    i = i+1

outFile.close()





