2018-05: Alchemical Reduction

library(stringi)
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
dt <- readLines("input.txt")
dt <- unlist(strsplit(dt, ""))

Part 1

reduced <- TRUE
while(reduced) {
  old <- length(dt)
  for (x in 1:(old - 1)) {
    if (dt[x] != dt[x + 1] & toupper(dt[x]) == toupper(dt[x + 1])) {
      dt[c(x, x + 1)] <- ""
      reduced <- TRUE
    }
  }
  dt <- dt[dt != ""]
  if(old == length(dt)) {
    reduced <- FALSE
  }
}
length(dt)
[1] 10598

Part 2

sapply(1:26, function(l) {
  tmp <- stri_replace_all_regex(dt, paste0(letters[l], "|", LETTERS[l]), "")
  reduced <- TRUE
  while (reduced) {
    old <- length(tmp)
    for (x in 1:(old - 1)) {
      if (tmp[x] != tmp[x + 1] & toupper(tmp[x]) == toupper(tmp[x + 1])) {
        tmp[c(x, x + 1)] <- ""
        reduced <- TRUE
      }
    }
    tmp <- tmp[tmp != ""]
    if (old == length(tmp)) {
      reduced <- FALSE
    }
  }
  length(tmp)
}) |>
  min()
[1] 5312