a counterintuitive property of coin-tossing: If Alice tosses a coin until she sees a head followed by a tail, and Bob tosses a coin until he sees two heads in a row, then on average, Alice will require four tosses while Bob will require six tosses
Can I demonstrate this in R?
Let’s make Alice and Bob flip coins:
Code
# returns the number of flips needed till the start of the patternflips_till_pattern <-function(pattern) { a <-rbinom(n=50,size=1,prob =0.5) # simulate tossing a coin 50 times.# make a string of the form "Heads-Tails..." showing the sequence of random results str <-paste(stringr::str_replace_all(stringr::str_replace_all(a,"1","Heads"),"0","Tails"), collapse ='-')# a list of all the indices in the string where pattern holds inds <-c(1, unlist(gregexpr(pattern, str))) m <-substring(str, head(inds, -1), tail(inds, -1)) ln <-lengths(strsplit(m, '-'))cumsum(c(ln[1], ln[-1] -1))[1]+1}
Playing this game 1000 times, here’s the average number of flips needed to get “Heads-Tails”
Now, you could say the above solution is terribly inelegant. There’s gotta be a way to implement this in a single line. But one advantage of my crude, string-based approach is that I can easily test other versions of the game.
For example, here’s the number of flips needed to get the pattern “Heads-Heads-Heads”