library(tidyverse)
Day 6
Advent of Code: Worked Solutions
Setup
Import libraries:
Disable scientific formatting when displaying large numbers:
options(scipen = 999)
Read input from file:
<- scan("../input/day06.txt", sep = ",", quiet = TRUE) input
Part 1
At any given point in time, we can only have fish with ages 0-8. We track the state of our system by logging counts of how many fish exist in each age bucket. To begin, we construct the initial state as a vector of counts for each age, filling with zeroes for ages not present:
<- input |>
init enframe(name = NULL, value = "age") |>
summarize(n = n(), .by = age) |>
complete(age = 0:8, fill = lst(n = 0)) |>
pull(n) |>
as.numeric()
Define a function to compute the count of fish on the next day given a fish count on the current day. All counts shift down one unit in age. Fish at age 0 all move to age 6 and create a new age-8 fish.
<- \(x) c(x[2:7], x[8] + x[1], x[9], x[1]) age_up
Define a function to run the simulation for n days and count the total fish at the end:
<- function(init, n_days) {
count_fish reduce(1:n_days, \(acc, nxt) age_up(acc), .init = init) |>
sum()
}
Count the total fish after 80 days:
count_fish(init, 80)
Part 2
Count the total fish after 256 days:
count_fish(init, 256)