-
Notifications
You must be signed in to change notification settings - Fork 0
/
d20.R
56 lines (50 loc) · 1.1 KB
/
d20.R
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
parse <- function(f) {
x <- data.frame(val = as.integer(readLines(f)))
x$current_pos <- seq_len(nrow(x))
x$prv <- x$current_pos - 1
x$prv[1] <- nrow(x)
x$nxt <- x$current_pos + 1
x$nxt[nrow(x)] <- 1
x
}
solve <- function(d, iters = 1, key = 1L) {
d$val <- d$val * key
for (j in 1:iters) {
for (i in seq_len(nrow(d))) {
d$nxt[d$prv[i]] <- d$nxt[i]
d$prv[d$nxt[i]] <- d$prv[i]
moves <- d$val[i] %% (nrow(d) - 1)
p <- d$nxt[i]
while (moves > 0) {
p <- d$nxt[p]
moves <- moves - 1
}
d$nxt[i] <- p
d$prv[i] <- d$prv[d$nxt[i]]
d$nxt[d$prv[i]] <- i
d$prv[d$nxt[i]] <- i
}
}
pointer <- which(d$val == 0)
s <- 0
for (j in 1:3) {
for (i in 1:1000) pointer <- d$nxt[pointer]
s <- s + d$val[pointer]
}
format(s, digits = 16)
}
part1 <- function(d) {
solve(d)
}
part2 <- function(d) {
solve(d, 10, 811589153)
}
test <- function() {
d <- parse("../inputs/d20-test.txt")
stopifnot(part1(d) == "3")
stopifnot(part2(d) == "1623178306")
}
test()
d <- parse("../inputs/d20-input.txt")
part1(d)
part2(d)