-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd05.R
54 lines (45 loc) · 1.33 KB
/
d05.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
parse_stacks <- function(input) {
count <- max(as.integer(strsplit(trimws(input[which(input == "") - 1]),
"\\s+")[[1]]))
parse_single <- function(index) {
index <- (index * 4) - 2
stack <- substr(input, index, index)
stack <- stack[1:(which(stack == "")[1] - 2)]
stack[trimws(stack) != ""]
}
lapply(1:count, parse_single)
}
parse_moves <- function(input) {
input <- input[(1 + which(input == "")):length(input)]
read.csv(text = gsub("[a-z ]+", ",", input),
col.names = c("", "move", "from", "to"), header = FALSE)
}
parse <- function(input) {
list(stacks = parse_stacks(input), moves = parse_moves(input))
}
solve <- function(d, part1 = FALSE) {
for (i in seq_len(nrow(d$moves))) {
move <- d$moves[i, ]
lift <- d$stacks[[move$from]][1:move$move]
if (part1) lift <- rev(lift)
d$stacks[[move$from]] <-
d$stacks[[move$from]][(move$move + 1):length(d$stacks[[move$from]])]
d$stacks[[move$to]] <- c(lift, d$stacks[[move$to]])
}
paste0(lapply(d$stacks, `[[`, 1), collapse = "")
}
part1 <- function(d) {
solve(d, TRUE)
}
part2 <- function(d) {
solve(d)
}
test <- function() {
d <- parse(readLines("../inputs/d05-test.txt"))
stopifnot(part1(d) == "CMZ")
stopifnot(part2(d) == "MCD")
}
test()
d <- parse(readLines("../inputs/d05-input.txt"))
part1(d)
part2(d)