commit 2dcde482dafa08128e47e430679d868ad4a5361f
parent 9b44bf6e9f09fa23967bd471e421b2355c2ed340
Author: Eamon Caddigan <ec@eamoncaddigan.net>
Date: Fri, 5 Dec 2025 12:19:23 -0800
Solve day 05, part 1
Diffstat:
| A | src/day05.R | | | 74 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 74 insertions(+), 0 deletions(-)
diff --git a/src/day05.R b/src/day05.R
@@ -0,0 +1,74 @@
+#!/usr/bin/env Rscript
+
+source("src/utils.R")
+
+test_input <- c(
+ "3-5",
+ "10-14",
+ "16-20",
+ "12-18",
+ "",
+ "1",
+ "5",
+ "8",
+ "11",
+ "17",
+ "32"
+)
+puzzle_input <- aoc_input(5)
+
+parse_input <- function(input_lines) {
+ blank_idx <- which(input_lines == "")
+ parsed_input <- list()
+
+ parsed_input$fresh_ranges <- input_lines[1:(blank_idx - 1)] |>
+ strsplit("-") |>
+ unlist() |>
+ as.numeric() |>
+ matrix(nrow = blank_idx - 1, byrow = TRUE)
+ parsed_input$fresh_ranges <- parsed_input$fresh_ranges[order(
+ parsed_input$fresh_ranges[, 1], parsed_input$fresh_ranges[, 2]
+ ), ]
+
+ parsed_input$ingredient_ids <- input_lines[(blank_idx + 1):length(input_lines)] |>
+ as.numeric() |>
+ sort()
+
+ parsed_input
+}
+
+test_ingredients <- function(ingredient_ids, fresh_ranges) {
+ is_fresh <- rep(NA, length(ingredient_ids))
+
+ fresh_idx <- 1
+ for (ingredient_idx in seq_along(ingredient_ids)) {
+ while (
+ fresh_idx <= nrow(fresh_ranges) &&
+ fresh_ranges[fresh_idx, 2] < ingredient_ids[ingredient_idx]
+ ) {
+ fresh_idx <- fresh_idx + 1
+ }
+ if (fresh_idx > nrow(fresh_ranges)) {
+ is_fresh[ingredient_idx:length(ingredient_ids)] <- FALSE
+ break
+ }
+ is_fresh[ingredient_idx] <- ingredient_ids[ingredient_idx] >= fresh_ranges[fresh_idx, 1]
+ }
+ is_fresh
+}
+
+part1 <- function(input_lines) {
+ input_parsed <- parse_input(input_lines)
+ sum(test_ingredients(input_parsed$ingredient_ids, input_parsed$fresh_ranges))
+}
+
+test_part1 <- function() {
+ stopifnot(part1(test_input) == 3)
+}
+
+main <- function() {
+ test_part1()
+ cat("Part 1 solution: ", part1(puzzle_input), "\n")
+}
+
+main()