-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14.R
44 lines (40 loc) · 1 KB
/
14.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
library(tidyverse)
input <- read_lines("input14") %>%
str_split("") %>%
do.call(what = rbind)
input <- cbind("#", rbind("#", input, "#"), "#")
north <- function(input) {
for (j in 1:ncol(input))
for (i in 1:nrow(input))
if (input[i,j] == "#")
last_obs <- i
else if (input[i,j] == "O") {
input[i,j] <- "."
input[last_obs + 1,j] <- "O"
last_obs <- last_obs + 1
}
input
}
rotate_right <- function(mat) {
t(mat)[,ncol(mat):1]
}
loads <- NULL
mat <- list()
cycles <- 1000000000
for (i in 1:cycles) {
# All tilts
for (j_ in 1:4)
input <- north(input) %>% rotate_right
# Compute load
load <- sum(apply(input, 1, \(x) sum(x == "O")) * (nrow(input):1 - 1))
loads <- c(loads, load)
# Keep track of previous loads
str <- input %>% unlist %>% paste(collapse = "")
if (!is.null(mat[[str]])) {
start <- mat[[str]]
len <- diff(which(loads == loads[start]))
print(loads[start + (cycles - start) %% len])
break
} else
mat[[str]] <- i
}