# Libraries
library(tidyverse)
library(unglue)
# Read input from file
<- read_lines("../input/day15.txt", skip_empty_rows = TRUE) |>
input str_split_1(",")
Day 15
Advent of Code: Worked Solutions
Setup
Part 1
Define a function that converts a character string into a hash value as defined by the specs:
<- function(str) {
ascii_hash reduce(
.x = utf8ToInt(str),
.f = ~ ((.x + .y) * 17) %% 256,
.init = 0
) }
Separate the input at the commas, run the ASCII hash on each item, and sum the result:
|>
input map_int(ascii_hash) |>
sum()
[1] 511215
Part 2
Define a function to place lenses in the appropriate boxes as defined by the input sequence:
<- function(boxes, str) {
hashmap <- str_extract(str, "[a-z]+")
label <- ascii_hash(label) + 1
box_num <- str_extract(str, "-|=")
operation
if (operation == "=")
<- parse_number(str)
boxes[[box_num]][[label]] if (operation == "-")
<- discard_at(boxes[[box_num]], label)
boxes[[box_num]]
boxes }
Define a function to compute the focusing power of the lenses in the final box arrangement:
<- function(boxes) {
focusing_power |>
boxes imap(\(box, box_num) {
imap(unname(box), \(lens, lens_num) {
as.integer(box_num) + 1) * lens_num * lens
(
})|>
}) unlist() |>
sum()
}
Run on puzzle input:
<- map(set_names(0:255), ~ list())
init_boxes
|>
input reduce(hashmap, .init = init_boxes) |>
focusing_power()
[1] 236057