Skip to content

Instantly share code, notes, and snippets.

@xvrdm
Last active December 4, 2021 20:55
Show Gist options
  • Save xvrdm/cc5c3d85847b42dfa2c13d67c616cb65 to your computer and use it in GitHub Desktop.
Save xvrdm/cc5c3d85847b42dfa2c13d67c616cb65 to your computer and use it in GitHub Desktop.
Advent of Code 2021 in R - Day 2
library(tidyverse)
input <- readr::read_lines("days/d02/data.txt") %>%
stringr::str_split(" ")
# Challenge 1
hor <- input %>%
purrr::keep(~ .[1] == "forward") %>%
purrr::map_dbl(~as.numeric(.[2])) %>%
sum
dep <- input %>%
purrr::discard(~ .[1] == "forward") %>%
purrr::map_dbl(~ ifelse(.[1] == "down", as.numeric(.[2]), -as.numeric(.[2]))) %>%
sum
hor * dep
# Challenge 2
gps <- input %>%
purrr::reduce(function(acc, nxt) {
x <- as.numeric(nxt[2])
if (nxt[1] == "down") {
purrr::list_modify(acc, aim=acc$aim + x)
} else if (nxt[1] == "up") {
purrr::list_modify(acc, aim=acc$aim - x)
} else {
purrr::list_modify(acc, depth=acc$depth + acc$aim * x, hor=acc$hor + x)
}
}, .init = list(aim=0, depth=0, hor=0))
gps$depth * gps$hor
# Challenge 2 with S3
update_state <- function(current, x) {
UseMethod("update_state", x)
}
update_state.forward <- function(current, x) {
purrr::list_modify(current,
depth=current$depth + current$aim * unclass(x),
hor=current$hor + unclass(x))
}
update_state.up <- function(current, x) {
purrr::list_modify(current, aim=current$aim - unclass(x))
}
update_state.down <- function(current, x) {
purrr::list_modify(current, aim=current$aim + unclass(x))
}
input %>%
purrr::map(~structure(as.numeric(.[2]), class=.[1])) %>%
purrr::reduce(update_state,
.init = list(aim=0, depth=0, hor=0)) %>%
with(depth * hor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment