-
Notifications
You must be signed in to change notification settings - Fork 1
/
day09.Rmd
58 lines (49 loc) · 1.48 KB
/
day09.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
---
title: "--- Day 9: Encoding Error ---"
author: Fleur Kelpin
date: Dec 9, 2020
output: github_document
---
```{r message=FALSE, warning=FALSE}
library(tidyverse)
input <- readr::read_csv("day09.txt")[[1]]
as_tibble(input)
```
# Part 1
The first step of attacking the weakness in the XMAS data is to find the first
number in the list (after the preamble) which is not the sum of two of the 25
numbers before it. **What is the first number that does not have this
property?**
```{r}
window <- 25
invalid <- function(i) {
number <- input[[i]]
preamble <- input[(i - window):i - 1]
!any(preamble %in% (number - preamble))
}
part1 <- seq(window + 1, length(input)) %>%
detect_index(invalid) %>%
{ input[[window + .]] }
part1
```
# Part 2
The final step in breaking the XMAS encryption relies on the invalid number you
just found: you must find a contiguous set of at least two numbers in your list
which sum to the invalid number from step 1.
To find the encryption weakness, add together the smallest and largest number in
this contiguous range.
**What is the encryption weakness in your XMAS-encrypted list of numbers?**
```{r}
contiguous_range <- function(start, window) {
input[start:(start + window - 1)]
}
find_start <- function(window) {
detect_index(
seq(length(input) - window),
~ sum(contiguous_range(.x, window)) == part1
)
}
window <- detect(seq(2, length(input)), ~ find_start(.) > 0)
start <- find_start(window)
contiguous_range(start, window) %>% { min(.) + max(.) }
```