In: Math
Write an R function max.streak(p) that gives the length of the maximum "streak" of either all heads or all tails in 100 flips of a (possibly biased) coin whose probabilty of showing heads is pp.
Use your function to determine the expected length (rounded to the nearest integer) of the maximum streak seen in 100 flips of a coin when the probability of seeing "heads" is 0.700.70.
As a check of your work, note that the expected length of the maximum streak seen in 100 flips of a fair coin should be very close to 7.
R function with appropriate comments -
max.streak <- function(p) {
x = sample(c(0,1), 100, replace = TRUE, prob = c(1-p, p)) #Generate
100 samples of 100 flips
count.head = 0 #Initialize Head Count to 0
count.tail = 0 #Initialize Tail Count to 0
max.head.streak = 0 #Initialize Max streak of Head to 0
max.tail.streak = 0 #Initialize Max streak of Tail to 0
for(i in 1:100) {
if(x[i] == 0) { # IF Tail occurs
if(max.head.streak < count.head) { #If max streak of heads is
less than current streak
max.head.streak = count.head #replace the max streak of heads by
the currect streak
}
count.head = 0 #Initialize Head Count to 0 as tail occurs
count.tail = count.tail + 1 #Increment the count of tail
}
if(x[i] == 1) { # IF Head occurs
count.head = count.head + 1 #Increment the count of head
if(max.tail.streak < count.tail) { #If max streak of tails is
less than current streak
max.tail.streak = count.tail #replace the max streak of heads by
the currect streak
}
count.tail = 0 #Initialize Tail Count to 0 as tail occurs
}
}
return(max(max.head.streak, max.tail.streak))
}
max.streak(0.7)
On running the code, I got the output of maximum streak as 11. The output will change for different runs.