library(tidyverse)Day 3
Advent of Code: Worked Solutions
Setup
Import libraries:
Disable scientific notation to display all digits of large numbers:
options(scipen = 999)Read text input from file:
input <- read_lines("../input/day03.txt") |>
str_split("") |>
map(as.numeric)Part 1
For each number, take the largest possible single digit NOT in the final location, and combine it with the largest following digit:
input |>
map_dbl(\(x) {
tens <- which.max(head(x, -1))
ones <- max(tail(x, -tens))
x[tens] * 10 + ones
}) |>
sum()Part 2
Define a recursive function which looks for the first through nth digits:
joltage <- function(input, n, init = "") {
if (n == 0)
return(as.numeric(init))
posn <- input |>
discard_at(length(input) - seq_len(n - 1) + 1) |>
which.max()
joltage(discard_at(input, 1:posn), n - 1, str_c(init, input[posn]))
}Run on puzzle input with 12 digits and sum the result:
input |>
map_dbl(\(x) joltage(x, 12)) |>
sum()