Advent of Code 2020

3.R 808B

123456789101112131415161718192021222324
  1. library(stringr)
  2. library(dplyr)
  3. input <- read.table("input3.txt", stringsAsFactors = FALSE, comment.char = '')[[1]] %>% str_split("")
  4. # actually a transposed matrix of the original
  5. input <- sapply(input, function(x) {x == '#'})
  6. width <- nrow(input)
  7. height <- ncol(input)
  8. # Unroll! Actually this is not needed
  9. # iv <- as.vector(input)
  10. grad <- function(map, down, across) {
  11. # Horizontal and vertical coordinates
  12. v <- seq(1, ncol(map), down)
  13. h <- ((0:(length(v) - 1) * across) %% nrow(map)) + 1
  14. # get vals at coordinates
  15. apply(cbind(h, v), 1, function(x) {map[x[1], x[2]]})
  16. }
  17. # Part a (3:1 slope)
  18. sum(grad(input, 1, 3))
  19. # Part b (1:1, 3:1, 5:1, 7:1, 1:2 slopes)
  20. prod(sum(grad(input, 1, 1)), sum(grad(input, 1, 3)), sum(grad(input, 1, 5)), sum(grad(input, 1, 7)), sum(grad(input, 2, 1)))