commit 62b2eb241aab95b8e6e7047deb18ed1214cde74f
parent e32ec9ee60192eb5a49b48830318adfaedf58cd3
Author: Eamon Caddigan <ec@eamoncaddigan.net>
Date: Sat, 6 Dec 2025 21:07:40 -0800
Solve day 06, part 2
Diffstat:
1 file changed, 31 insertions(+), 0 deletions(-)
diff --git a/src/day06.R b/src/day06.R
@@ -40,9 +40,40 @@ test_part1 <- function() {
stopifnot(part1(test_input) == 4277556)
}
+
+parse_part2 <- function(input_lines) {
+ char_mat <- input_lines |>
+ strsplit("", fixed = TRUE) |>
+ (\(x) matrix(unlist(x), ncol = length(x), byrow = FALSE))()
+ is_separator <- apply(char_mat == " ", 1, all)
+ list(
+ numbers = char_mat[!is_separator, 1:(ncol(char_mat) - 1)] |>
+ apply(1, \(x) paste(x, collapse = "")) |>
+ as.numeric() |>
+ split(cumsum(is_separator)[!is_separator]),
+ operators = char_mat[char_mat[, ncol(char_mat)] != " ", ncol(char_mat)]
+ )
+}
+
+part2 <- function(input_lines) {
+ input_parsed <- parse_part2(input_lines)
+ mapply(
+ \(x, y) if (y == "+") sum(x) else prod(x),
+ input_parsed$numbers,
+ input_parsed$operators
+ ) |>
+ sum()
+}
+
+test_part2 <- function() {
+ stopifnot(part2(test_input) == 3263827)
+}
+
main <- function() {
test_part1()
cat(sprintf("Part 1 solution: %0.0f\n", part1(puzzle_input)))
+ test_part2()
+ cat(sprintf("Part 2 solution: %0.0f\n", part2(puzzle_input)))
}
main()