-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday08.R
105 lines (76 loc) · 2.63 KB
/
day08.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Requires the library "numbers"
day08 <- readLines("puzzle_input/input_day08.txt")
directions <- unlist(strsplit(day08[1], ""))
day08 <- day08[-(1:2)]
day08 <- as.data.frame(do.call(rbind, strsplit(day08, " = ")))
names(day08) <- c("node", "options")
day08$options <- gsub("[()]", "", day08$options)
options <- as.data.frame(do.call(rbind, strsplit(day08$options, ", ")))
names(options) <- c("L", "R")
day08 <- cbind.data.frame(day08, options)
day08$options <- NULL
## PART 1 ----------------------------------------------------------------------
start <- Sys.time()
temp_node <- "AAA"
n_steps <- 0
while (temp_node != "ZZZ") {
temp_direction <-
directions[
ifelse(
(n_steps + 1) %% length(directions) == 0,
length(directions),
(n_steps + 1) %% length(directions)
)
]
temp_node <- day08[day08$node == temp_node, temp_direction]
n_steps <- n_steps + 1
}
n_steps
# 18673
Sys.time() - start
## PART 2 ----------------------------------------------------------------------
# As expected, brute-forcing this takes too long. Instead, figure out at which
# intervals each start node hits a node ending with Z (and when the pattern
# repeats for each node), then figure out at which point all nodes converge at
# a node ending with Z.
start <- Sys.time()
temp_nodes <- day08$node[grepl("..A", day08$node)]
first_z <- vector("character", length(temp_nodes))
z_visits <- vector("list", length(temp_nodes))
z_visits <- lapply(z_visits, function(x) vector("numeric", 0))
for (i_node in seq_along(temp_nodes)) {
n_steps <- 0
temp_node <- temp_nodes[i_node]
go_flag <- TRUE
while (go_flag) {
temp_direction <-
directions[
ifelse(
(n_steps + 1) %% length(directions) == 0,
length(directions),
(n_steps + 1) %% length(directions)
)
]
temp_node <- day08[day08$node == temp_node, temp_direction]
n_steps <- n_steps + 1
if (grepl("..Z", temp_node)) {
if (first_z[i_node] == "") {
first_z[i_node] <- temp_node
z_visits[[i_node]] <- c(z_visits[[i_node]], n_steps)
} else {
if (first_z[i_node] != temp_node) {
z_visits[[i_node]] <- c(z_visits[[i_node]], n_steps)
} else {
go_flag <- FALSE
}
}
}
}
}
# Luckily, each node only visits a single Z location repeatedly. We only need
# to figure out when they are all in that location at the same time.
z_visits <- unlist(z_visits)
# ... which can be determined using the least common multiple
options(scipen = 999)
numbers::mLCM(z_visits)
Sys.time() - start