commit 180e6d60336ea92ff5c3c0b9835723e1125ee511
parent 1f053c4aebdebb8ac7a82bce5a9be77b9dda3d8e
Author: Eamon Caddigan <ec@eamoncaddigan.net>
Date: Mon, 1 Dec 2025 16:19:39 -0800
Solve day 01, parts 1 and 2
I meant to commit the part 1 solution separately.
Diffstat:
| A | src/day01.R | | | 72 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | src/utils.R | | | 12 | ++++++++++++ |
2 files changed, 84 insertions(+), 0 deletions(-)
diff --git a/src/day01.R b/src/day01.R
@@ -0,0 +1,72 @@
+source("src/utils.R")
+
+apply_turn <- function(position_and_zero_crossings, turn_instruction) {
+ turn_size <- as.integer(substr(turn_instruction, 2, nchar(turn_instruction)))
+ old_pos <- position_and_zero_crossings[1]
+
+ if (substr(turn_instruction, 1, 1) == "L") {
+ new_pos <- old_pos - turn_size
+ new_zero_crossings <- abs(new_pos %/% 100) +
+ (new_pos %% 100 == 0) - (old_pos %% 100 == 0)
+ } else {
+ new_pos <- old_pos + turn_size
+ new_zero_crossings <- new_pos %/% 100
+ }
+
+ c(new_pos %% 100, position_and_zero_crossings[2] + new_zero_crossings)
+}
+
+count_zeros <- function(x) {
+ sum(vapply(x, \(x) (x[1] %% 100) == 0, logical(1)))
+}
+
+part1 <- function(input_lines) {
+ Reduce(apply_turn, input_lines, c(50, 0), accumulate = TRUE) |>
+ count_zeros()
+}
+
+test_part1 <- function() {
+ part1_test_input <- "L68
+L30
+R48
+L5
+R60
+L55
+L1
+L99
+R14
+L82"
+ stopifnot(
+ part1(strsplit(part1_test_input, "\n")[[1]]) == 3
+ )
+}
+
+part2 <- function(input_lines) {
+ Reduce(apply_turn, input_lines, c(50, 0), accumulate = FALSE)[2]
+}
+
+test_part2 <- function() {
+ part2_test_input <- "L68
+L30
+R48
+L5
+R60
+L55
+L1
+L99
+R14
+L82"
+ stopifnot(
+ part2(strsplit(part2_test_input, "\n")[[1]]) == 6
+ )
+}
+
+main <- function() {
+ puzzle_input <- aoc_input(1)
+ test_part1()
+ cat("Part 1 solution:", part1(puzzle_input), "\n")
+ test_part2()
+ cat("Part 2 solution:", part2(puzzle_input), "\n")
+}
+
+main()
diff --git a/src/utils.R b/src/utils.R
@@ -0,0 +1,12 @@
+aoc_input <- function(day, year = 2025) {
+ if (!file.exists("~/.aoc")) {
+ stop("AoC session ID must be present in ~/.aoc")
+ }
+ con <- url(
+ sprintf("https://adventofcode.com/%d/day/%d/input", year, day),
+ headers = c("Cookie" = paste0("session=", readLines("~/.aoc")))
+ )
+ puzzle_input <- readLines(con)
+ close(con)
+ puzzle_input
+}