Day 6

Advent of Code: Worked Solutions

About
Date

December 6, 2021

Setup

Import libraries:

library(tidyverse)

Disable scientific formatting when displaying large numbers:

options(scipen = 999)

Read input from file:

input <- scan("../input/day06.txt", sep = ",", quiet = TRUE)

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:

init <- input |> 
  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.

age_up <- \(x) c(x[2:7], x[8] + x[1], x[9], x[1])

Define a function to run the simulation for n days and count the total fish at the end:

count_fish <- function(init, n_days) {
  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)