-
Notifications
You must be signed in to change notification settings - Fork 1
/
day15.Rmd
66 lines (58 loc) · 1.86 KB
/
day15.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
59
60
61
62
63
64
65
66
---
title: "--- Day 15: Rambunctious Recitation ---"
author: Fleur Kelpin
date: Dec 15, 2020
output: github_document
---
```{r message=FALSE, warning=FALSE}
library(tidyverse)
input <- tibble(number = readLines("day15.txt")) %>%
separate_rows(number, sep = ",", convert = TRUE)
input
```
# Part 1
In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number:
* If that was the first time the number has been spoken, the current player says 0.
* Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken.
So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat).
```{r}
game <- c(input$number)
while (length(game) < 2020) {
occurred_last <- tail(which(game == last(game)), 2)
game <- append(
game,
if (length(occurred_last) == 1) {
0
} else {
occurred_last[[2]] - occurred_last[[1]]
}
)
}
last(game)
```
# Part 2
Given your starting numbers, what will be the 30000000th number spoken?
We need a map here, but this is problematic in R.
I tried with hash(), had to use as.character() on the keys and it took half an
hour to compute this.
Later found out that a large vector works way faster:
```{r}
game <- rep(0, 30000000)
for (i in 1:(length(input$number) - 1)) {
number <- input$number[[i]]
game[number + 1] <- i
}
last_number <- last(input$number)
tictoc::tic()
for (i in (length(input$number) + 1):30000000) {
occurred_last <- game[[last_number + 1]]
game[[last_number + 1]] <- i - 1
last_number <- if (occurred_last == 0) {
0
} else {
i - 1 - occurred_last
}
}
tictoc::toc()
last_number
```