library(tidyverse)
library(here)
library(rlang)
Part 1
Another fairly straight forwad puzzle. We are given an algorithm that we need to follow. The algorithm is as follows:
- Determine the ASCII code for the current character of the string.
- Increase the current value by the ASCII code you just determined.
- Set the current value to itself multiplied by 17.
- Set the current value to the remainder of dividing itself by 256.
As always let’s read in the puzzle input and tidy the input into something we can work with.
<- read_lines(
data here('posts', 'aoc-2023-d15', 'puzzle-input.txt')
)
<- data |>
data str_split(',') |>
unlist() |>
as_tibble()
data
# A tibble: 4,000 × 1
value
<chr>
1 fzl-
2 tcjp=8
3 vkjr=9
4 xs-
5 jktcpk=3
6 gzp-
7 kfsxsd-
8 zxkv=7
9 fxz-
10 pj=7
# ℹ 3,990 more rows
Now let’s write a helper function that can help us decode the hash based on the provided algorithm.
<- \(hash) {
hash_decoder
<- hash |> str_split('') |> unlist()
hash
<- 0
current_value walk(hash, \(x) {
<- utf8ToInt(x)
ascii_code <- (current_value + ascii_code) * 17
current_value <<- current_value %% 256
current_value
})
return(current_value)
}
Finally let’s apply the function across all of the values.
<- data |>
data rowwise() |>
mutate(
hash = hash_decoder(value)
|>
) ungroup()
data
# A tibble: 4,000 × 2
value hash
<chr> <dbl>
1 fzl- 41
2 tcjp=8 54
3 vkjr=9 243
4 xs- 200
5 jktcpk=3 23
6 gzp- 238
7 kfsxsd- 160
8 zxkv=7 119
9 fxz- 149
10 pj=7 62
# ℹ 3,990 more rows
The solution of the puzzle is simply the sum of all the hash values.
sum(data$hash)
Reuse
Citation
BibTeX citation:
@online{luu2023,
author = {Luu, Michael},
title = {Advent of {Code} 2023, {Day} 15},
date = {2023-12-24},
langid = {en}
}
For attribution, please cite this work as:
Luu, Michael. 2023. “Advent of Code 2023, Day 15.” December
24, 2023.