Skip to content

Instantly share code, notes, and snippets.

@trinker
Created October 5, 2021 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trinker/c0ff00202b98f274dff583beaffcd3f2 to your computer and use it in GitHub Desktop.
Save trinker/c0ff00202b98f274dff583beaffcd3f2 to your computer and use it in GitHub Desktop.
## https://youtu.be/094y1Z2wpJg
library(tidyverse)
collatz <- function(x){
v = c(x)
i = 1
while (v[i] != 1){
z = v[i]
i = i + 1
if (z %% 2 == 0){
v[i] = z/2
} else {
v[i] = 3*z+1
}
}
steps = length(v) - 1
list(
original = x,
total_stopping_time = steps,
data = tibble::tibble(
original = x,
hailstones = v,
time = seq(1, steps + 1)
)
)
}
collatz(27)
111
r <- sample.int(1000000000, 1000)
samps <- lapply(r, collatz)
pdat = dplyr::bind_rows(lapply(samps, function(x) x$data))
mean(sapply(samps, function(x) x$total_stopping_time))
pdat %>%
ggplot(aes(x = time, y = hailstones, group = original)) +
geom_line(show.legend = FALSE, alpha = .025, color = 'black')+
coord_cartesian(ylim = c(0, 5000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment