Advent of Code 2021 - Day 2

Hi, welcome to the solution to day two of Advent of Code 2021. Please check out the puzzle at https://adventofcode.com/2021/day/2

# Data --------------------------------------------------------------------
dir_data <- read.csv(file = "day_two",  col.names = c("direction", "value"), 
                     header = FALSE, sep = " ")
head(dir_data)
##   direction value
## 1   forward     9
## 2      down     3
## 3      down     8
## 4   forward     2
## 5        up     3
## 6   forward     5

Part 1:

# Solution -----------------------------------------------------------------
forward_pos <- sum(with(dir_data, value[direction == "forward"]))

depth_values <- within(with(dir_data, dir_data[direction != "forward",]), {
  depth_dir <- ifelse(direction == "up",  -value, value)
})

depth_pos <- sum(depth_values[, "depth_dir"])

(answer <- depth_pos * forward_pos)
## [1] 1451208

Part 2:

# Solution -----------------------------------------------------------------
dir_data <- within(dir_data, {
  aim <- ifelse(direction != "forward", value, 0)
  aim <- ifelse(aim != 0 & direction == "up", -aim, aim)
  aim <- cumsum(aim)
  hor_change <- ifelse(direction == "forward", value, 0)
  depth_change <- ifelse(direction == "forward", aim * value, 0)
})

hor_pos <- sum(dir_data[["hor_change"]])
depth_pos <- sum(dir_data[["depth_change"]])

(answer <- hor_pos * depth_pos)
## [1] 1620141160

See you tomorrow :)

Avatar
Moritz Mueller-Navarra

A Data Scientist using R

Related