Skip to content

Instantly share code, notes, and snippets.

@carlislerainey
Created October 30, 2015 10:22
Show Gist options
  • Select an option

  • Save carlislerainey/f8cb897382bdc345178f to your computer and use it in GitHub Desktop.

Select an option

Save carlislerainey/f8cb897382bdc345178f to your computer and use it in GitHub Desktop.
Code to simulate and calculate the number of switches and streaks in a series of coin tosses
calc_switches <- function(x) {
n <- length(x)
x0 <- x[1:(n - 1)]
x1 <- x[2:n]
switches <- sum(x0 != x1)
return(switches)
}
calc_streak <- function(x) {
longest_streak <- 0
current_streak <- 1
n <- length(x)
for (i in 2:n) {
current_streak <- ifelse(x[i] == x[i - 1], current_streak + 1, 1)
longest_streak <- ifelse(current_streak > longest_streak, current_streak, longest_streak)
}
return(longest_streak)
}
x <- rbinom(50, 1, .5)
calc_streak(x)
n_sims <- 1000
switches <- longest_streak <- rep(NA, n_sims)
for (i in 1:n_sims) {
x <- rbinom(200, 1, .5)
switches[i] <- calc_switches(x)
longest_streak[i] <- calc_streak(x)
}
df <- data.frame(switches, longest_streak)
library(ggplot2)
ggplot(df, aes(x = switches, y = longest_streak)) +
geom_point(position = "jitter")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment