Advent of Code 2020 Day 3

Author

Nathan Moore

— Day 3: Toboggan Trajectory —

The toboggan you hire does not have much (any) steering.

Starting at the top-left corner of your map and following a slope of right 3 and down 1, how many trees would you encounter?

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.6
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.1     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.2.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
inputfile <- here::here("2020", "data-2020-03.txt")
trees_slim <- read.delim(inputfile, header = FALSE)

Write a function for movement

Note: this is different math from python, where zero index lets us reset easily if we go too wide, here we only reset for explicitly larger than the width of the field.

move_tobog <- function(rght, dwn, course) {
  x_pos = 1
  y_pos = 1
  course_len = length(course[[1]])
  width = str_count(course[[1]][1])
  trees = 0
  while (y_pos <= course_len) {
    # check for tree
    if (str_sub(course[[1]][[y_pos]], x_pos, x_pos) == "#") {
      trees = trees + 1
    }
    # move the toboggan
    # x_pos <- (x_pos + rght) %% width
    if (x_pos + rght > width) { 
        x_pos <- (x_pos + rght) %% width
    } else {
        x_pos <- x_pos + rght        
    }
    y_pos <- y_pos + dwn
    # print(cat(x_pos, y_pos))
  }
  return(trees)
}

move_tobog(3, 1, trees_slim)
[1] 270

— Part Two —

Can we find the best way to get down?

What do you get if you multiply together the number of trees encountered on each of the listed slopes?

# part one is right 3 down 1, part two is others
paths <- tibble::tibble(
  right = c(3, 1, 5, 7, 1), 
  down = c(1, 1, 1, 1, 2)
)

# the old map doing work
paths_hits <- paths %>% 
  mutate(
    trees_hit = map2_dbl(right, down, move_tobog, trees_slim)
  )

# part two answer
reduce(paths_hits$trees_hit, `*`)
[1] 2122848000