Skip to content

Commit 740bc00

Browse files
committed
Optimize 2024 day 20 part 2 by not creating set
All cheats are unique by construction.
1 parent 718ffde commit 740bc00

File tree

2 files changed

+4
-6
lines changed

2 files changed

+4
-6
lines changed

src/main/scala/eu/sim642/adventofcode2024/Day20.scala

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,15 @@ object Day20 {
2828
trait Part {
2929
val maxCheat: Int
3030

31-
def findCheats(grid: Grid[Char]): Set[Cheat] = {
31+
def findCheats(grid: Grid[Char]): Iterable[Cheat] = {
3232
val forwardSearch = gridGraphSearch(grid, 'S', 'E')
3333
val forwardResult = BFS.search(forwardSearch)
3434
val backwardSearch = gridGraphSearch(grid, 'E', 'S')
3535
val backwardResult = BFS.search(backwardSearch)
3636

3737
val noCheatDistance = forwardResult.target.get._2
3838

39-
// TODO: optimize
40-
41-
(for {
39+
for {
4240
(row, y) <- grid.view.zipWithIndex
4341
(cell, x) <- row.view.zipWithIndex
4442
if cell != '#'
@@ -55,7 +53,7 @@ object Day20 {
5553
cheatDistance = forwardResult.distances(start) + (startCheat + endCheat) + backwardResult.distances(end)
5654
//if cheatDistance <= noCheatDistance
5755
save = noCheatDistance - cheatDistance
58-
} yield Cheat(start, end, save)).toSet
56+
} yield Cheat(start, end, save)
5957
}
6058

6159
def countGoodCheats(grid: Grid[Char]): Int = findCheats(grid).count(_.save >= 100)

src/test/scala/eu/sim642/adventofcode2024/Day20Test.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class Day20Test extends AnyFunSuite {
6060
assert(cheats(76) == 3)
6161
}
6262

63-
test("Part 2 input answer") { // TODO: optimize (~4.3s)
63+
test("Part 2 input answer") {
6464
assert(Part2.countGoodCheats(parseGrid(input)) == 1011325)
6565
}
6666
}

0 commit comments

Comments
 (0)