12: JSAbacusFramework.io

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

 Also loading:  cipheR data.table dplyr purrr slider stringr tidyverse glue
library(jsonlite)
dt <- readLines("input.json")

Part 1

Surprisingly easy. Just had a small regex typo with ? instead of +.

dt |>
  str_extract_all("(-?[0-9]+)") |>
  unlist() |>
  as.numeric() |>
  sum(na.rm = TRUE)
[1] 191164

Part 2

What a nightmare! I got the answer wrong 16 times and tried so many things. String replacement, string reduction, listing, unlisting, whatever I could think of. I eventually remembered rrapply and had a wacky solution that didn’t work at all. I took a break for a few days and really read the documentation on how = "recurse". Then it was just a matter of realizing that .xname in the documentation is not the same as names(x) and I was good to go!

dt |>
  parse_json() |>
  list() |>
  rrapply::rrapply(
    \(o) { any(o == "red") & any(names(o) %in% letters) },
    \(x) { return(list("a" = "red")) }, 
    how = "recurse",
    classes = "list") |>
  unlist() |>
  as.numeric() |>
  suppressWarnings() |>
  sum(na.rm = TRUE)
[1] 87842