[Code]
collatz_step <- function(n) {
if (n %% 2 == 0) n / 2 else 3 * n + 1
}
# apply the rule until the sequence reaches 1
current <- 6
values <- current
while (current != 1) {
current <- collatz_step(current)
values <- c(values, current)
}
steps <- seq_along(values) - 1
collatz_seq <- tibble::tibble(step = steps, value = values)
collatz_plot <- ggplot2::ggplot(collatz_seq) +
ggplot2::aes(x = step, y = value) +
ggplot2::geom_line() +
ggplot2::geom_point(size = 2) +
ggplot2::scale_x_continuous(breaks = steps) +
ggplot2::labs(x = "step", y = "value")
collatz_plot