Advent of Code: Day 13
I started to have cold and my foggy brain had a difficult time with today’s problem. I’m pretty sure the code of part 2 would eventually produce the right answer, but it’s very slow and the answer is a high numnber. Maybe I’ll revisit if I find the time at a later point. One one star for me today…
Part 1
raw_input <- "0: 3
1: 2
4: 4
6: 4"
input <- cat(raw_input, file = "advent-data/2017-12-13-advent-day13-test.txt")
library(tidyverse)
build_sequence <- function(amplitude, element) {
stopifnot(amplitude >= 0)
if (amplitude <= 1)
return(amplitude)
res <- rep(c(1:amplitude, (amplitude-1):2) ,
max(1, ceiling(element / amplitude)))
if (length(res) < element) browser()
res[element]
}
scanner_position <- function(lst, l) {
map_int(lengths(lst), ~ build_sequence(., l))
}
get_severity <- function(input) {
input <- read_delim(input, delim = ": ",
col_names = c("layer", "depth")) %>%
mutate_all(as.numeric)
full_input <- tibble(
layer = full_seq(input$layer, 1)
)
full_input <- left_join(full_input, input, by = "layer") %>%
mutate(depth = replace(depth, is.na(depth), 0))
firewall <- pmap(full_input, function(layer, depth) integer(depth))
severity <- 0
for (i in seq_along(firewall)) {
scan_pos <- scanner_position(firewall, i)
if (scan_pos[i] == 1) {
severity <- severity + (i-1) * full_input$depth[full_input$layer == (i - 1)]
}
}
severity
}
get_severity("advent-data/2017-12-13-advent-day13-test.txt")
## Parsed with column specification:
## cols(
## layer = col_integer(),
## depth = col_character()
## )
## [1] 24
get_severity("advent-data/2017-12-13-advent-day13.txt")
## Parsed with column specification:
## cols(
## layer = col_integer(),
## depth = col_character()
## )
## [1] 2604
Part 2
get_delay <- function(input) {
input <- read_delim(input, delim = ": ",
col_names = c("layer", "depth")) %>%
mutate_all(as.numeric)
full_input <- tibble(
layer = full_seq(input$layer, 1)
)
full_input <- left_join(full_input, input, by = "layer") %>%
mutate(depth = replace(depth, is.na(depth), 0))
firewall <- pmap(full_input, function(layer, depth) integer(depth))
delay <- 27060
severity <- 1
while (severity != 0) {
severity <- 0
delay <- delay + 1
for (i in seq_along(firewall)) {
scan_pos <- scanner_position(firewall, i + delay)
if (scan_pos[i] == 1) {
severity <- severity + (i-1) *
full_input$depth[full_input$layer == (i - 1)]
}
}
if (delay %% 1000 == 0)
message("delay: ", delay, " -- severity: ", severity)
}
delay
}
get_delay("advent-data/2017-12-13-advent-day13-test.txt")
get_delay("advent-data/2017-12-13-advent-day13.txt")
Comments