advent_of_code_2025

My (attempted) solutions to the 2025 Advent of Code
git clone https://git.eamoncaddigan.net/advent_of_code_2025.git
Log | Files | Refs | README

day01.R (1405B)


      1 source("src/utils.R")
      2 
      3 apply_turn <- function(position_and_zero_crossings, turn_instruction) {
      4   turn_size <- as.integer(substr(turn_instruction, 2, nchar(turn_instruction)))
      5   old_pos <- position_and_zero_crossings[1]
      6 
      7   if (substr(turn_instruction, 1, 1) == "L") {
      8     new_pos <- old_pos - turn_size
      9     new_zero_crossings <- abs(new_pos %/% 100) +
     10       (new_pos %% 100 == 0) - (old_pos %% 100 == 0)
     11   } else {
     12     new_pos <- old_pos + turn_size
     13     new_zero_crossings <- new_pos %/% 100
     14   }
     15 
     16   c(new_pos %% 100, position_and_zero_crossings[2] + new_zero_crossings)
     17 }
     18 
     19 count_zeros <- function(x) {
     20   sum(vapply(x, \(x) (x[1] %% 100) == 0, logical(1)))
     21 }
     22 
     23 part1 <- function(input_lines) {
     24   Reduce(apply_turn, input_lines, c(50, 0), accumulate = TRUE) |>
     25     count_zeros()
     26 }
     27 
     28 test_part1 <- function() {
     29   part1_test_input <- "L68
     30 L30
     31 R48
     32 L5
     33 R60
     34 L55
     35 L1
     36 L99
     37 R14
     38 L82"
     39   stopifnot(
     40     part1(strsplit(part1_test_input, "\n")[[1]]) == 3
     41   )
     42 }
     43 
     44 part2 <- function(input_lines) {
     45   Reduce(apply_turn, input_lines, c(50, 0), accumulate = FALSE)[2]
     46 }
     47 
     48 test_part2 <- function() {
     49   part2_test_input <- "L68
     50 L30
     51 R48
     52 L5
     53 R60
     54 L55
     55 L1
     56 L99
     57 R14
     58 L82"
     59   stopifnot(
     60     part2(strsplit(part2_test_input, "\n")[[1]]) == 6
     61   )
     62 }
     63 
     64 main <- function() {
     65   puzzle_input <- aoc_input(1)
     66   test_part1()
     67   cat("Part 1 solution:", part1(puzzle_input), "\n")
     68   test_part2()
     69   cat("Part 2 solution:", part2(puzzle_input), "\n")
     70 }
     71 
     72 main()