-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday9.R
43 lines (36 loc) · 938 Bytes
/
day9.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
#Day 9
setwd("C:/Users/David.simons/Documents/advent of code")
input <- readLines("day9.txt")
#part 1----
getTotal <- function(input) {
input <- gsub("!.", "", input) #remove invalidation
input <- gsub("<.*?>","", input) #remove garbage (minimally)
input <- gsub(",", "", input) #remove commas
chars <- unlist(strsplit(input, NULL))
total <- 0
level <- 0
for (c in chars) {
if (c == "{") {
level <- level + 1
} else {
total <- total + level
level <- level - 1
}
}
total
}
print(getTotal(input))
#part 2 ----
countGarbage <- function(input) {
input <- gsub("!.", "", input) #remove invalidation
chars <- unlist(strsplit(input, NULL))
total <- 0
open <- F
for (c in chars) {
if (c == "<" && !open) open <- T
else if (c == ">" && open) open <- F
else if (open) total <- total + 1
}
total
}
print(countGarbage(input))