library(tidyr)
library(dplyr)
library(readr)
library(stringr)
Part 1
Input
<-"input.txt" sample
Code
<- read_delim(file = sample, delim = " ",col_names = c("name","value")) %>%
input replace_na(replace = list(value = 0))
<-
result %>%
input mutate(cycle = cumsum(case_when(name == "addx" ~2,
TRUE ~ 1)),
register = 1 + lag(cumsum(value),1)) %>%
complete(cycle = 1:240) %>%
fill(register,.direction = "up") %>%
mutate(signal = cycle * register)
%>%
result filter(cycle %in% seq(20, 220, by=40)) %>%
summarise(sum(signal))
%>%
result mutate(row = (cycle -1) %/% 40,
col = (cycle -1) %% 40,
pixel = ifelse(col >= register -1 & col <= register +1,"#",".")) %>%
group_by(row) %>%
summarise(paste0(pixel, collapse=""))