-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd14.R
77 lines (67 loc) · 1.35 KB
/
d14.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
parse <- function(f) {
lapply(readLines(f), function(x) {
x <- strsplit(x, " -> ")[[1]]
lapply(x, function(x) as.integer(strsplit(x, ",")[[1]]))
})
}
part1 <- function(d, part2 = FALSE) {
maxy <- 1
sand <- matrix(data = 0, nrow = 180, ncol = 700)
for (g in seq_along(d)) {
draw <- d[[g]]
ox <- draw[[1]][1]
oy <- draw[[1]][2] + 1
maxy <- max(oy, maxy)
for (h in 2:length(draw)) {
px <- draw[[h]][1]
py <- draw[[h]][2] + 1
maxy <- max(py, maxy)
sand[oy:py, ox:px] <- 1
ox <- px
oy <- py
}
}
if (part2) {
sand[maxy + 2, 1:700] <- 1
maxy <- maxy + 2
}
g <- 0
abyss <- FALSE
while (!abyss) {
x <- 500
y <- 1
if (sand[y, x] != 0) break
while (TRUE) {
if (y >= maxy) {
abyss <- TRUE
break
}
if (sand[y + 1, x] == 0) {
y <- y + 1
} else if (sand[y + 1, x - 1] == 0) {
x <- x - 1
y <- y + 1
} else if (sand[y + 1, x + 1] == 0) {
x <- x + 1
y <- y + 1
} else {
break
}
}
if (!abyss) {
sand[y, x] <- 2
g <- g + 1
}
}
g
}
part2 <- function(d) part1(d, TRUE)
test <- function() {
d <- parse("../inputs/d14-test.txt")
stopifnot(part1(d) == 24)
stopifnot(part2(d) == 93)
}
test()
d <- parse("../inputs/d14-input.txt")
part1(d)
part2(d)