day06.R (1844B)
1 #!/usr/bin/env Rscript 2 3 source("src/utils.R") 4 5 test_input <- c( 6 "123 328 51 64 ", 7 " 45 64 387 23 ", 8 " 6 98 215 314", 9 "* + * + " 10 ) 11 puzzle_input <- aoc_input(6) 12 13 parse_input <- function(input_lines) { 14 split_lines <- strsplit(trimws(input_lines), "\\s+") 15 list( 16 numbers = split_lines[1:(length(split_lines) - 1)] |> 17 unlist() |> 18 as.numeric() |> 19 matrix(nrow = length(split_lines) - 1, byrow = TRUE), 20 operators = split_lines[[length(split_lines)]] 21 ) 22 } 23 24 solve_problems <- function(numbers, operators) { 25 sum(c( 26 apply(numbers[, operators == "+"], 2, sum), 27 apply(numbers[, operators == "*"], 2, prod) 28 )) 29 } 30 31 part1 <- function(input_lines) { 32 input_parsed <- parse_input(input_lines) 33 solve_problems( 34 input_parsed$numbers, 35 input_parsed$operators 36 ) 37 } 38 39 test_part1 <- function() { 40 stopifnot(part1(test_input) == 4277556) 41 } 42 43 44 parse_part2 <- function(input_lines) { 45 char_mat <- input_lines |> 46 strsplit("", fixed = TRUE) |> 47 (\(x) matrix(unlist(x), ncol = length(x), byrow = FALSE))() 48 is_separator <- apply(char_mat == " ", 1, all) 49 list( 50 numbers = char_mat[!is_separator, 1:(ncol(char_mat) - 1)] |> 51 apply(1, \(x) paste(x, collapse = "")) |> 52 as.numeric() |> 53 split(cumsum(is_separator)[!is_separator]), 54 operators = char_mat[char_mat[, ncol(char_mat)] != " ", ncol(char_mat)] 55 ) 56 } 57 58 part2 <- function(input_lines) { 59 input_parsed <- parse_part2(input_lines) 60 mapply( 61 \(x, y) if (y == "+") sum(x) else prod(x), 62 input_parsed$numbers, 63 input_parsed$operators 64 ) |> 65 sum() 66 } 67 68 test_part2 <- function() { 69 stopifnot(part2(test_input) == 3263827) 70 } 71 72 main <- function() { 73 test_part1() 74 cat(sprintf("Part 1 solution: %0.0f\n", part1(puzzle_input))) 75 test_part2() 76 cat(sprintf("Part 2 solution: %0.0f\n", part2(puzzle_input))) 77 } 78 79 main()