commit aa551c12b65a4f1adad9a7b2a233f37efd52629e
parent d32cd88acd6b005a1c5cd24115b77e3f2ca36690
Author: Eamon Caddigan <ec@eamoncaddigan.net>
Date: Mon, 8 Dec 2025 15:18:41 -0800
Solve day 08, part 1
Diffstat:
| A | src/day08.R | | | 87 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 87 insertions(+), 0 deletions(-)
diff --git a/src/day08.R b/src/day08.R
@@ -0,0 +1,87 @@
+#!/usr/bin/env Rscript
+
+source("src/utils.R")
+
+test_input <- c(
+ "162,817,812",
+ "57,618,57",
+ "906,360,560",
+ "592,479,940",
+ "352,342,300",
+ "466,668,158",
+ "542,29,236",
+ "431,825,988",
+ "739,650,466",
+ "52,470,668",
+ "216,146,977",
+ "819,987,18",
+ "117,168,530",
+ "805,96,715",
+ "346,949,466",
+ "970,615,88",
+ "941,993,340",
+ "862,61,35",
+ "984,92,344",
+ "425,690,689"
+)
+puzzle_input <- aoc_input(8)
+
+parse_input <- function(input_lines) {
+ input_lines |>
+ strsplit(",") |>
+ lapply(as.numeric) |>
+ (\(x) do.call(rbind, x))()
+}
+
+order_distances <- function(distmat) {
+ # Put the pairs from the distance matrix in increasing order
+ which(lower.tri(distmat), arr.ind = TRUE)[order(distmat), ]
+}
+
+greedy_connect <- function(coords, steps) {
+ # Circuit IDs for each junction box
+ coord_circuits <- seq_len(nrow(coords))
+ # Junction box (coordinate) IDs for each circuit
+ circuit_coords <- as.list(seq_along(coord_circuits))
+
+ pair_order <- coords |>
+ dist() |>
+ order_distances()
+ stopifnot(steps <= nrow(pair_order))
+
+ for (i in seq_len(steps)) {
+ c1 <- coord_circuits[pair_order[i, 1]]
+ c2 <- coord_circuits[pair_order[i, 2]]
+ if (c1 < c2) {
+ coord_circuits[circuit_coords[[c2]]] <- c1
+ circuit_coords[[c1]] <- union(circuit_coords[[c1]], circuit_coords[[c2]])
+ circuit_coords[c2] <- list(NULL)
+ } else if (c1 > c2) {
+ coord_circuits[circuit_coords[[c1]]] <- c2
+ circuit_coords[[c2]] <- union(circuit_coords[[c1]], circuit_coords[[c2]])
+ circuit_coords[c1] <- list(NULL)
+ }
+ }
+
+ circuit_coords
+}
+
+part1 <- function(input_lines, steps) {
+ input_lines |>
+ parse_input() |>
+ greedy_connect(steps) |>
+ vapply(length, integer(1)) |>
+ sort(decreasing = TRUE) |>
+ (\(x) prod(x[1:3]))()
+}
+
+test_part1 <- function() {
+ stopifnot(part1(test_input, 10) == 40)
+}
+
+main <- function() {
+ test_part1()
+ cat("Part 1 solution: ", part1(puzzle_input, 1000), "\n")
+}
+
+main()