From 19fb541e3a314ae2ba3254f615d0fee859ce5b8e Mon Sep 17 00:00:00 2001 From: Oscar Molnar Date: Fri, 6 Dec 2024 12:43:46 +0000 Subject: [PATCH] Switched to an iterative algorithm for day 6 part 2 for 3 orders of magnitude speedup --- .../kotlin/com/tymscar/day06/part2/part2.kt | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/2024/kotlin/src/main/kotlin/com/tymscar/day06/part2/part2.kt b/2024/kotlin/src/main/kotlin/com/tymscar/day06/part2/part2.kt index 580c526..767a855 100644 --- a/2024/kotlin/src/main/kotlin/com/tymscar/day06/part2/part2.kt +++ b/2024/kotlin/src/main/kotlin/com/tymscar/day06/part2/part2.kt @@ -67,18 +67,23 @@ data class Position(val y: Int, val x: Int) { } } -private tailrec fun doesItLoop( - currentPath: List>, +private fun doesItLoop( + start: Pair, extraObstacle: Position, - grid: List>, + grid: List> ): Boolean { - val (currentPosition, currentDirection) = currentPath.last() + var (currentPosition, currentDirection) = start + val visited = HashSet>() - val (nextPosition, nextDir) = currentPosition.getNextValidPosition(currentDirection, extraObstacle, grid) - return when { - nextPosition.isOutsideGrid(grid) -> false - (nextPosition to nextDir) in currentPath -> true - else -> doesItLoop(currentPath + (nextPosition to nextDir), extraObstacle, grid) + while (true) { + if ((currentPosition to currentDirection) in visited) return true + visited.add(currentPosition to currentDirection) + + val (nextPosition, nextDir) = currentPosition.getNextValidPosition(currentDirection, extraObstacle, grid) + if (nextPosition.isOutsideGrid(grid)) return false + + currentPosition = nextPosition + currentDirection = nextDir } } @@ -105,13 +110,9 @@ fun solve(input: String): String { }.filterNotNull() } - val startingList = listOf((startingPosition to Direction.UP)) + val starting = (startingPosition to Direction.UP) return possibleObstaclePositions - .mapIndexed { index, position -> - if (index % 100 == 0) println("Processing $index") - doesItLoop(startingList, position, grid) - } - .count { it } + .count { doesItLoop(starting, it, grid) } .toString() }