-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathd24.R
70 lines (59 loc) · 1.69 KB
/
d24.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
parse_input <- function(f) {
d <- unlist(lapply(readLines(f),
function(x) gsub(" ", "", gsub(" @ ", ",", x))))
d <- read.csv(text = d, sep = ",", header = FALSE,
col.names = c("px", "py", "pz", "vx", "vy", "vz"))
d$grad_xy <- d$vy / d$vx
d
}
intersect_xy <- function(px1, py1, grad1, px2, py2, grad2) {
c1 <- py1 - (px1 * grad1)
c2 <- py2 - (px2 * grad2)
if ((grad1 == grad2) && (c1 != c2)) return(NA)
x0 <- (c2 - c1) / (grad1 - grad2)
y0 <- (grad1 * x0) + c1
c(x0, y0)
}
in_past <- function(x0, x1, vx) {
(((x0 < x1) && (vx > 0)) ||
((x0 > x1) && (vx < 0)))
}
part1 <- function(d, xy1 = 200000000000000,
xy2 = 400000000000000) {
tot <- 0
for (i in seq_len(nrow(d) - 1)) {
p1 <- d[i, ]
for (j in (i + 1):nrow(d)) {
p2 <- d[j, ]
ixy <- intersect_xy(p1$px, p1$py, p1$grad_xy,
p2$px, p2$py, p2$grad_xy)
if (any(is.na(ixy))) {
next
}
if ((ixy[1] >= xy1) && (ixy[1] <= xy2) &&
(ixy[2] >= xy1) && (ixy[2] <= xy2)) {
if (in_past(ixy[1], p1$px, p1$vx) || in_past(ixy[2], p1$py, p1$vy)) {
next
}
if (in_past(ixy[1], p2$px, p2$vx) || in_past(ixy[2], p2$py, p2$vy)) {
next
}
tot <- tot + 1
}
}
}
tot
}
part2 <- function(d, file) {
file <- file.path(getwd(), file)
system2("python", c("wes_p2.py", file), stdout = TRUE, stderr = TRUE)
}
test <- function() {
d <- parse_input("../inputs/d24-test.txt")
stopifnot(part1(d, 7, 27) == 2)
stopifnot(part2(d, "../inputs/d24-test.txt") == 47)
}
test()
d <- parse_input("../inputs/d24-input.txt")
part1(d)
part2(d, "../inputs/d24-input.txt")