2021-05: Hydrothermal Venture

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.5.0 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
library(data.table)

Attaching package: 'data.table'

The following objects are masked from 'package:dplyr':

    between, first, last

The following object is masked from 'package:purrr':

    transpose
library(stringr)

Part 1

# part 1
dt <- data.frame(fread("input.txt"))
dt <- data.table("x1" = dt[, "V1"] + 1,
                 "y1" = as.numeric(str_split(dt$V2, " -> ", 
                                             simplify = TRUE)[,1]) + 1,
                 "x2" = as.numeric(str_split(dt$V2, " -> ", 
                                             simplify = TRUE)[,2]) + 1,
                 "y2" = dt[, "V3"] + 1)[x1 == x2 | y1 == y2,]
mx <- data.frame(matrix(data = 0, nrow = max(dt), ncol = max(dt)))

for(r in 1:nrow(dt)) {
  mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]] <- 
    mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]] + 1
}

length(mx[mx > 1])
[1] 4728

Part 2

# part 2
dt <- data.frame(fread("input.txt"))
dt <- data.table("x1" = dt[, "V1"] + 1,
                 "y1" = as.numeric(str_split(dt$V2, " -> ", 
                                             simplify = TRUE)[,1]) + 1,
                 "x2" = as.numeric(str_split(dt$V2, " -> ", 
                                             simplify = TRUE)[,2]) + 1,
                 "y2" = dt[, "V3"] + 1) %>%
  .[, at :=  (x1 == y2 & x2 == y1) |
             (x1 == y1 & x2 == y2) | 
             (abs(x2 - x1) == abs(y2 - y1))] 
mx <- matrix(data = 0, nrow = max(dt), ncol = max(dt))

for(r in 1:nrow(dt)) {
  ifelse(dt$at[r],
    diag(mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]]) <- 
      diag(mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]]) + 1,
    mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]] <- 
      mx[dt$x1[r]:dt$x2[r], dt$y1[r]:dt$y2[r]] + 1)
}

length(mx[mx > 1])
[1] 17717