2016-01: No Time for a Taxicab

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.4.1 
✔ 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)
dt <- readLines("input.txt") |> 
  str_split(", ", simplify = FALSE) |> 
  unlist() |>
  str_match_all("([RL])([0-9]*)") |> 
  list() |> 
  rbindlist() |>
  t() |>
  data.table() |>
  `colnames<-`(c("input", "dir", "dis")) |>
  mutate(dis = as.integer(dis))
head(dt)
   input dir dis
1:    R4   R   4
2:    R5   R   5
3:    L5   L   5
4:    L5   L   5
5:    L3   L   3
6:    R2   R   2

Part 1

dt$deg <- 0
for(i in 2:nrow(dt)) {
  if(dt$dir[i] == "R") { dt$deg[i] <- dt$deg[i-1] + 90 }
  else {dt$deg[i] <- dt$deg[i-1] - 90}
}
dt |>
  mutate(deg = deg %% 360, 
         dis = ifelse(deg %in% c(180, 270), -dis, dis)) |>
  group_by(deg) |>
  summarise(n = sum(dis)) |>
  pull(n) |>
  sum()
[1] 250

Part 2

points <- matrix(c(ifelse(dt$dir[1] == "R", dt$dis[1], -dt$dis[1]), 0), 1, 2)
for (j in 2:nrow(dt)) {
  tmp <- dt[1:j,]
  tmp$deg <- 0
  for (i in 2:j) {
    if (tmp$dir[i] == "R") { tmp$deg[i] <- tmp$deg[i - 1] + 90 }
    else {  tmp$deg[i] <- tmp$deg[i - 1] - 90 }
  }
  tmp |>
    mutate(deg = deg %% 360,
           dis = ifelse(deg %in% c(180, 270), -dis, dis)) |>
    group_by(deg) |>
      summarise(n = sum(dis)) |>
      ungroup() |>
    mutate(deg = ifelse(deg %% 360 %in% c(0, 180), TRUE, FALSE)) |>
    group_by(deg) |>
      summarise(n = sum(n)) |>
      ungroup() |>
    pull(n) -> point
  points <- rbind(points, unname(point))
}
points <- rbind(t(c(0, 0)), points)

tmp <- t(c(NA, NA))

for(i in 1:(nrow(points) - 1)) {
  tmp <- 
    rbind(tmp, cbind(points[i,1]:points[i+1,1], points[i,2]:points[i+1,2]))
}
Warning in cbind(points[i, 1]:points[i + 1, 1], points[i, 2]:points[i + : number
of rows of result is not a multiple of vector length (arg 1)
tmp <- tmp[-1,]
for(i in 1:(nrow(tmp) - 1)) {
  if(all(tmp[i,] == tmp[i+1,])) {
    tmp[i,] <- t(c(NA, NA))
  }
}
tmp <- na.omit(tmp)
sum(tmp[duplicated(tmp),][1,])
[1] 151