Skip to content

Commit 66c26a7

Browse files
committed
add day 10
1 parent 3ea40aa commit 66c26a7

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

2021/day10.R

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#####SETUP#####
2+
library(magrittr)
3+
library(dequer)
4+
5+
#####INPUT#####
6+
fin <- file("day10.in", open = "r")
7+
vals <- readLines(fin) %>%
8+
strsplit(split = "", fixed = TRUE)
9+
close(fin)
10+
11+
#####UTILITY#####
12+
OPEN <- c("(", "[", "{", "<")
13+
CLOSE<- c(")", "]", "}", ">")
14+
names(OPEN) <- CLOSE
15+
names(CLOSE) <- OPEN
16+
first_mistake <- function(line) {
17+
s <- stack()
18+
19+
for (i in line) {
20+
21+
if (i %in% OPEN) push(s, i)
22+
23+
else if (i %in% CLOSE) {
24+
25+
last <- pop(s)
26+
if (OPEN[i] != last) return(i)
27+
28+
} else {
29+
stop(paste("UNEXPECTED CHAR:", i))
30+
}
31+
}
32+
33+
return(" ")
34+
}
35+
36+
complete_str <- function(line) {
37+
s <- stack()
38+
39+
for (i in line) {
40+
41+
if (i %in% OPEN) push(s, i)
42+
else if (i %in% CLOSE) pop(s)
43+
44+
}
45+
46+
ans <- ""
47+
while (length(s) > 0) {
48+
ans <- paste0(ans, CLOSE[pop(s)])
49+
}
50+
51+
return(ans)
52+
}
53+
54+
VALS1 <- c(")" = 3, "]" = 57, "}" = 1197, ">" = 25137, " " = 0)
55+
get_points1 <- function(chr) {
56+
vapply(
57+
X = chr,
58+
USE.NAMES = FALSE,
59+
FUN.VALUE = numeric(1),
60+
FUN = function(curr) {
61+
VALS1[curr]
62+
}
63+
)
64+
}
65+
66+
VALS2 <- c(")" = 1, "]" = 2, "}" = 3, ">" = 4)
67+
get_points2 <- function(chr) {
68+
chr <- chr %>%
69+
strsplit(split = "", fixed = TRUE) %>%
70+
unlist
71+
72+
counter <- 0
73+
74+
for (i in chr) {
75+
counter <- counter * 5 + VALS2[i]
76+
}
77+
78+
return(counter)
79+
}
80+
81+
#####PART 1#####
82+
vals %>%
83+
lapply(FUN = first_mistake) %>%
84+
lapply(FUN = get_points1) %>%
85+
unlist %>%
86+
sum
87+
88+
#####PART 2#####
89+
incomplete <- lapply(X = vals, FUN = first_mistake) %>%
90+
unlist %>%
91+
equals(" ") %>%
92+
which
93+
94+
vals[incomplete] %>%
95+
lapply(FUN = complete_str) %>%
96+
lapply(FUN = get_points2) %>%
97+
unlist %>%
98+
median

0 commit comments

Comments
 (0)