Skip to content

Instantly share code, notes, and snippets.

@malcolmbarrett
Created September 10, 2026 21:49
Show Gist options
  • Select an option

  • Save malcolmbarrett/8f9f733f87532384a4328e23a4ca38a2 to your computer and use it in GitHub Desktop.

Select an option

Save malcolmbarrett/8f9f733f87532384a4328e23a4ca38a2 to your computer and use it in GitHub Desktop.
# measure the average number of steps a random walker takes in two
# dimensions to return to origin for the first time by simulating
# the random walk multiple times.
library(tidyverse)
# walk through an integer grid one step at a time
# report the number of steps on first return to the origin
steps_on_first_return <- function(max_steps = 10000L) {
x <- 0L
y <- 0L
# directions 1 through 4 are right, left, up, and down.
dx <- c(1L, -1L, 0L, 0L)
dy <- c(0L, 0L, 1L, -1L)
for (step in seq_len(max_steps)) {
direction <- sample.int(4L, size = 1L)
# go 1 unit in 1 direction only
x <- x + dx[direction]
y <- y + dy[direction]
# if returned to orgin, report steps
if (x == 0L && y == 0L) {
return(step)
}
}
# the walker has not returned within the step limit;
# its return steps is unknown
NA_integer_
}
# as.integer(Sys.Date()) for today gives me the seed
set.seed(20706)
n_walks <- 5000L
max_steps <- 10000L
walks <- tibble(walk = seq_len(n_walks)) |>
mutate(
return_steps = map_int(walk, \(i) steps_on_first_return(max_steps)),
returned = !is.na(return_steps)
)
return_summary <- walks |>
summarise(
n_walks = n(),
step_limit = max_steps,
n_returned = sum(returned),
n_unfinished = sum(!returned),
proportion_returned = mean(returned),
mean_steps_all = mean(return_steps),
mean_steps_among_returns = if (any(returned)) {
mean(return_steps[returned])
} else {
NA_real_
}
)
return_summary
# show first-return times only for walks that returned within the step limit.
walks |>
filter(returned) |>
ggplot(aes(x = return_steps)) +
geom_histogram(bins = 10, fill = "steelblue", color = "white") +
labs(
title = "Steps to first return",
subtitle = paste("Walks returning within", max_steps, "steps"),
x = "Steps",
y = "Number of walks"
) +
scale_x_log10() +
theme_minimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment