-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_15.Rmd
79 lines (60 loc) · 1.82 KB
/
day_15.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
67
68
69
70
71
72
73
74
75
76
77
78
79
# Rambunctious Recitation
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(crayon.enabled = NULL, # for when rendering on github actions
scipen = 999) # make sure we never print in scientific notation
library(tidyverse)
START_TIME <- Sys.time()
```
This is my attempt to solve [Day 15](https://adventofcode.com/2020/day/15).
```{r load data}
sample <- c(0,3,6)
actual <- c(12,1,16,3,11,0)
```
## Part 1
Ideally we would use a data type like a dictionary in Python for today's problem... but there isn't really a good
option in R. Instead I will just assign a vector that will be long enough for the solution. I'm going to make an
assumption that the largest number we will see will be less than the number of turns.
```{r}
solve <- function(input, turns) {
turn <- numeric(turns)
# first iterate over the input
for (i in seq_along(input)) {
p <- input[[i]]
# R is 1 indexed, make it 0
turn[[p + 1]] <- i
}
# now continue for the rest of the turns
for (i in (length(input) + 1):turns) {
# find out which value was spoke
t <- turn[[p + 1]]
# update the value of the turn
turn[[p + 1]] <- i - 1
# find which word is to be spoke
p <- ifelse(t == 0, 0, i - t - 1)
}
p
}
```
We can now test that our function works against the sample data:
```{r part 1 sample test}
solve(sample, 4) == "0"
solve(sample, 5) == "3"
solve(sample, 6) == "3"
solve(sample, 7) == "1"
solve(sample, 8) == "0"
solve(sample, 9) == "4"
solve(sample, 10) == "0"
solve(sample, 2020) == 436
```
We can now run our function on the actual data:
```{r part 1 actual}
solve(actual, 2020)
```
## Part 2
We don't need to change anything for part 2, other than the number of turns.
```{r part 2}
solve(actual, 30000000)
```
---
*Elapsed Time: `r round(Sys.time() - START_TIME, 3)`s*