library(tidyverse)
Day 2
Advent of Code: Worked Solutions
Setup
Import libraries:
Read input from file:
<- read_delim(
input "../input/day02.txt",
delim = " ",
col_names = c("dir", "value"),
show_col_types = FALSE
)
Part 1
Convert input values to final horizontal positions and depth values:
<- input |>
pos transmute(
dim = case_match(dir, "forward" ~ "horiz", c("up", "down") ~ "depth"),
value = case_match(dir, "up" ~ -value, .default = value)
|>
) summarize(value = sum(value), .by = dim)
Compute product of final horizontal position and depth:
prod(pos$value)
Part 2
Compute final horizontal position and depth value using the modified keyword meanings:
<- input |>
pos transmute(
aim = cumsum(case_match(dir, "down" ~ value, "up" ~ -value, .default = 0)),
horiz = cumsum(case_match(dir, "forward" ~ value, .default = 0)),
depth = cumsum(case_match(dir, "forward" ~ value * aim, .default = 0))
|>
) select(horiz, depth) |>
tail(n = 1)
Compute product of final horizontal position and depth:
$horiz * pos$depth pos