Skip to content

Commit

Permalink
Optimize 2024 day 20 part 2 by not creating set
Browse files Browse the repository at this point in the history
All cheats are unique by construction.
  • Loading branch information
sim642 committed Dec 20, 2024
1 parent 718ffde commit 740bc00
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 6 deletions.
8 changes: 3 additions & 5 deletions src/main/scala/eu/sim642/adventofcode2024/Day20.scala
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,15 @@ object Day20 {
trait Part {
val maxCheat: Int

def findCheats(grid: Grid[Char]): Set[Cheat] = {
def findCheats(grid: Grid[Char]): Iterable[Cheat] = {
val forwardSearch = gridGraphSearch(grid, 'S', 'E')
val forwardResult = BFS.search(forwardSearch)
val backwardSearch = gridGraphSearch(grid, 'E', 'S')
val backwardResult = BFS.search(backwardSearch)

val noCheatDistance = forwardResult.target.get._2

// TODO: optimize

(for {
for {
(row, y) <- grid.view.zipWithIndex
(cell, x) <- row.view.zipWithIndex
if cell != '#'
Expand All @@ -55,7 +53,7 @@ object Day20 {
cheatDistance = forwardResult.distances(start) + (startCheat + endCheat) + backwardResult.distances(end)
//if cheatDistance <= noCheatDistance
save = noCheatDistance - cheatDistance
} yield Cheat(start, end, save)).toSet
} yield Cheat(start, end, save)
}

def countGoodCheats(grid: Grid[Char]): Int = findCheats(grid).count(_.save >= 100)
Expand Down
2 changes: 1 addition & 1 deletion src/test/scala/eu/sim642/adventofcode2024/Day20Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class Day20Test extends AnyFunSuite {
assert(cheats(76) == 3)
}

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

0 comments on commit 740bc00

Please sign in to comment.