# Libraries
library(tidyverse)
# Read input from file
<- read_fwf("../input/day02.txt", col_types = "c") input
Day 2
Advent of Code: Worked Solutions
Setup
Part 1
# Format shapes/strategies as numbers 1-3 for modular arithmetic
<- tibble(
df opponent = as.numeric(factor(input$X1, levels = c("A", "B", "C"))),
strategy = as.numeric(factor(input$X2, levels = c("X", "Y", "Z")))
)
<- function(df) {
score_shape |>
df mutate(
self = strategy,
outcome = (self - opponent + 1) %% 3 * 3,
score = self + outcome
|>
) pull(score) |>
sum()
}
Run puzzle input:
score_shape(df)
[1] 15422
Part 2
<- function(df) {
score_outcome |>
df mutate(
self = (opponent + strategy) %% 3 + 1,
outcome = (strategy - 1) * 3,
score = self + outcome
|>
) pull(score) |>
sum()
}
score_outcome(df)
[1] 15442