Skip to content

Commit af99f1a

Browse files
committed
Optimize 2025 day 9 part 2 using 2D prefix sums
1 parent d3caeac commit af99f1a

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/main/scala/eu/sim642/adventofcode2025/Day9.scala

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,30 @@ object Day9 {
6666

6767
val outside = BFS.traverse(graphTraversal).nodes
6868

69+
val outsidePrefix = mutable.ArraySeq.fill(ys.size * 2 - 1 + 2, xs.size * 2 - 1 + 2)(0)
70+
for (y <- outsidePrefix.indices) {
71+
for (x <- outsidePrefix(y).indices) {
72+
outsidePrefix(y)(x) =
73+
(if (y >= 1) outsidePrefix(y - 1)(x) else 0) +
74+
(if (x >= 1) outsidePrefix(y)(x - 1) else 0) -
75+
(if (x >= 1 && y >= 1) outsidePrefix(y - 1)(x - 1) else 0) +
76+
(if (outside(Pos(x, y))) 1 else 0)
77+
}
78+
}
79+
80+
//for (row <- outsidePrefix) {
81+
// for (cell <- row)
82+
// print(s"$cell\t")
83+
// println()
84+
//}
85+
6986
def isValid(box: Box): Boolean = {
7087
val gridBox = Box(mapPos(box.min), mapPos(box.max))
71-
!gridBox.iterator.exists(outside)
88+
//!gridBox.iterator.exists(outside)
89+
(outsidePrefix(gridBox.max.y)(gridBox.max.x) -
90+
outsidePrefix(gridBox.min.y - 1)(gridBox.max.x) -
91+
outsidePrefix(gridBox.max.y)(gridBox.min.x - 1) +
92+
outsidePrefix(gridBox.min.y - 1)(gridBox.min.x - 1)) == 0
7293
}
7394

7495
(for {

src/test/scala/eu/sim642/adventofcode2025/Day9Test.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class Day9Test extends AnyFunSuite {
2727
assert(Part2.largestArea(parseRedTiles(exampleInput)) == 24)
2828
}
2929

30-
ignore("Part 2 input answer") { // TODO: optimize (~8.5s)
30+
test("Part 2 input answer") {
3131
assert(Part2.largestArea(parseRedTiles(input)) == 1474477524L)
3232
}
3333
}

0 commit comments

Comments
 (0)