Day 2

Advent of Code: Worked Solutions

About
Date

December 2, 2022

Setup

# Libraries
library(tidyverse)

# Read input from file
input <- read_fwf("../input/day02.txt", col_types = "c")

Part 1

# Format shapes/strategies as numbers 1-3 for modular arithmetic
df <- tibble(
  opponent = as.numeric(factor(input$X1, levels = c("A", "B", "C"))),
  strategy = as.numeric(factor(input$X2, levels = c("X", "Y", "Z")))
)

score_shape <- function(df) {
  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

score_outcome <- function(df) {
  df |> 
    mutate(
      self = (opponent + strategy) %% 3 + 1,
      outcome = (strategy - 1) * 3,
      score = self + outcome
    ) |>
    pull(score) |>
    sum()
}
score_outcome(df)
[1] 15442