-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday11.R
115 lines (82 loc) · 2.55 KB
/
day11.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Example input, if needed
# day11 <- readLines("puzzle_input/input_day11_exp.txt")
day11 <- readLines("puzzle_input/input_day11.txt")
day11 <- strsplit(day11, "")
day11 <- as.matrix(do.call(rbind, day11))
## PART 1 ----------------------------------------------------------------------
start <- Sys.time()
# If there's an empty row between the two galaxies, that needs to count n-times.
expansion <- 2
# Identify all rows and columns without galaxies.
empty_rows <- which(apply(day11, 1, function(x) all(x == ".")))
empty_cols <- which(apply(day11, 2, function(x) all(x == ".")))
# Find all galaxies
galaxies <- as.data.frame(which(day11 == "#", arr.ind = TRUE))
galaxies$id <- 1:nrow(galaxies)
# All pairs of galaxies
galaxy_pairs <- t(combn(galaxies$id, 2))
galaxy_distances <- vector("numeric", nrow(galaxy_pairs))
pb <-
txtProgressBar(
min = 0, max = length(galaxy_distances), initial = 0, style = 3
)
for (i in seq_along(galaxy_distances)) {
galaxy1 <- galaxies[galaxy_pairs[i, 1], c(1, 2)]
galaxy2 <- galaxies[galaxy_pairs[i, 2], c(1, 2)]
dist <- sum(abs(galaxy1 - galaxy2))
# Add expansion, i.e. number of empty rows + cols
dist <-
dist +
sum(
empty_rows > min(galaxy1$row, galaxy2$row) &
empty_rows < max(galaxy1$row, galaxy2$row)
) *
(expansion - 1)
dist <-
dist +
sum(
empty_cols > min(galaxy1$col, galaxy2$col) &
empty_cols < max(galaxy1$col, galaxy2$col)
) *
(expansion - 1)
galaxy_distances[i] <- dist
setTxtProgressBar(pb, i)
}
close(pb)
sum(galaxy_distances)
# 9693756
Sys.time() - start
## PART 2 ----------------------------------------------------------------------
start <- Sys.time()
expansion <- 1000000
galaxy_distances <- vector("numeric", nrow(galaxy_pairs))
pb <-
txtProgressBar(
min = 0, max = length(galaxy_distances), initial = 0, style = 3
)
for (i in seq_along(galaxy_distances)) {
galaxy1 <- galaxies[galaxy_pairs[i, 1], c(1, 2)]
galaxy2 <- galaxies[galaxy_pairs[i, 2], c(1, 2)]
dist <- sum(abs(galaxy1 - galaxy2))
# Add expansion, i.e. number of empty rows + cols
dist <-
dist +
sum(
empty_rows > min(galaxy1$row, galaxy2$row) &
empty_rows < max(galaxy1$row, galaxy2$row)
) *
(expansion - 1)
dist <-
dist +
sum(
empty_cols > min(galaxy1$col, galaxy2$col) &
empty_cols < max(galaxy1$col, galaxy2$col)
) *
(expansion - 1)
galaxy_distances[i] <- dist
setTxtProgressBar(pb, i)
}
close(pb)
sum(galaxy_distances)
# 717878258016
Sys.time() - start