2023

— R Day 2 Part 1 —

solve_day2_part1 <- function(input) {
   colour_max <- c("r" = 12, "g" = 13, "b" = 14)

   possible <- lapply(names(colour_max),
                      is_possible,
                      games = input,
                      max = colour_max)

   possible <- Reduce(`&`, possible)

   ids <- seq_along(input)
   sum(ids[possible])
}

is_possible <- function(colour, strings, games, max) {
  # all drawn for the colour per game
  pattern <- paste0("\\d+(?= ", colour, ")")
  values  <- stringi::stri_extract_all(games, regex = pattern)

  # highest drawn per game
  highest_values <- vapply(values, \(x) max(as.numeric(x)), numeric(1))

  # highest is possible per game
  vapply(highest_values, \(x) x <= max[colour], logical(1))
}
Run
aoc_source(day = 2, part = 1)

input = aoc_read(day = 2)

aoc_run(solve_day2_part1(input))
Elapsed: 0.005 seconds
Memory:  538 KB

— R Day 2 Part 2 —

solve_day2_part2 <- function(input) {
   colours <- c("r", "g", "b")

   minimums <- lapply(colours, minimum_cubes, games = input)
   powers   <- Reduce(`*`, minimums)

   sum(powers)
}

minimum_cubes <- function(colour, strings, games) {
  # all drawn for the colour per game
  pattern <- paste0("\\d+(?= ", colour, ")")
  values  <- stringi::stri_extract_all(games, regex = pattern)

  # highest drawn per game
  vapply(values, \(x) max(as.numeric(x)), numeric(1))
}
Run
aoc_source(day = 2, part = 2)

input = aoc_read(day = 2)

aoc_run(solve_day2_part2(input))
Elapsed: 0.004 seconds
Memory:  32 KB
Back to top