Skip to content

Instantly share code, notes, and snippets.

@aammd
Last active February 19, 2026 00:37
Show Gist options
  • Select an option

  • Save aammd/14e8b50ce7b5105421b9ef033301ac6f to your computer and use it in GitHub Desktop.

Select an option

Save aammd/14e8b50ce7b5105421b9ef033301ac6f to your computer and use it in GitHub Desktop.
clock stepping simulation
ids <- 1:12
take_step <- function(i){
x <- NA_integer_
if (i == 1) {
x <- sample(c(2, 12), size = 1)
} else if (i == 12) {
x <- sample(c(11, 1), size = 1)
} else {
x <- i + sample(c(-1, 1), size = 1)
}
return(x)
}
take_step(12)
library(tidyverse)
around_clock <- function(){
outs <- c(12,rep(NA_integer_, 300))
i <- 2
while(length(table(outs))<12) {
outs[i] <- take_step(outs[i-1])
i <- i + 1
}
cum_out <- cumsum(is.finite(outs))
# get the last one
last <- outs[which.max(cum_out)]
# get the length
len <- max(cum_out)
tibble::tibble(last, len, outs = list(outs))
}
dd <- around_clock()
dd$outs
sim_df <- purrr::map_df(1:1000, ~around_clock(), .id = "sim")
sim_df |>
count(last) |>
mutate(freq = n/1000) |>
ggplot(aes(x= last, y = freq)) + geom_point() +
scale_x_continuous(breaks = 1:11) +
ylim(c(0, 1)) +
geom_hline(yintercept = 1/11)
1/11
sim_df |>
ggplot(aes(x = len)) +
geom_histogram() +
geom_vline(xintercept = 66, col = "red", lwd = 2)
mean(sim_df$len-1)
sim_df |>
ggplot(aes(y = len, x = last)) +
geom_count(alpha = .5) +
theme_bw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment