2019-03: Crossed Wires

library(mistlecode)
To install `mistlecode` yourself, run `devtools::install_github('guslipkin/mistlecode')`.

 Also loading:  cipheR data.table dplyr purrr slider stringr tidyverse
dtMM <-
  readLines("input.txt") |>
  lapply(\(x) {
    strsplit(x, ",")[[1]] |>
      data.frame() |>
      `colnames<-`(c("col")) |>
      separate(col = "col", into = c("dir", "mag"), sep = 1) |>
      mutate(mag = as.integer(mag))
  })

Part 1

dtM <- lapply(dtMM, expand_directions, preserve_data = TRUE)

dtM[[1]] <- follow_directions(dtM[[1]], 0, 0, preserve_data = TRUE)
dtM[[2]] <- follow_directions(dtM[[2]], 0, 0, preserve_data = TRUE)

inner_join(dtM[[1]], dtM[[2]], by = c("row", "col")) |>
  mutate(dist = abs(row) + abs(col)) |>
  arrange(dist) |>
  head(1) |>
  pull(dist)
[1] 1264

Part 2

dtM[[1]] <- 
  dtM[[1]] |>
  mutate(step = row_number())
dtM[[2]] <- 
  dtM[[2]] |>
  mutate(step = row_number())

inner_join(dtM[[1]], dtM[[2]], by = c("row", "col")) |>
  mutate(steps = step.x + step.y) |>
  arrange(steps) |>
  head(1) |>
  pull(steps)
[1] 37390