From 43ebc459143e4a2729086b1233b6c14afeae9986 Mon Sep 17 00:00:00 2001 From: Matthew Hill Date: Mon, 16 Dec 2024 08:58:09 -0700 Subject: [PATCH] AoC 2024 Day 16 Code Cleanup Cleanup function names to better reflect what is being done, along with the type signature --- .../com/geistindersh/aoc/year2024/Day16.kt | 32 +++++++++++++++---- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/main/kotlin/com/geistindersh/aoc/year2024/Day16.kt b/src/main/kotlin/com/geistindersh/aoc/year2024/Day16.kt index 5034795..b85e170 100644 --- a/src/main/kotlin/com/geistindersh/aoc/year2024/Day16.kt +++ b/src/main/kotlin/com/geistindersh/aoc/year2024/Day16.kt @@ -22,7 +22,16 @@ class Day16( val path: List = emptyList(), ) - private fun shortestPathScore(): Long { + /** + * Get the minimum score required to traverse from [start] to [end] + * @param start The starting point + * @param end The ending point + * @return The minimum score from [start] to [end] + */ + private fun getScoreOfShortestPath( + start: Point2D, + end: Point2D, + ): Long { val queue = PriorityQueue(compareBy { it.score }).apply { add(Path(start)) } val seen = mutableSetOf>() while (queue.isNotEmpty()) { @@ -42,11 +51,20 @@ class Day16( return -1L } - private fun pointsForShortestPaths(): Set { - val minScore = shortestPathScore() + /** + * Get all possible shortest paths from [start] to [end] + * @param start The starting point + * @param end The ending point + * @return The shortest paths + */ + private fun getShortestPaths( + start: Point2D, + end: Point2D, + ): Set> { + val minScore = getScoreOfShortestPath(start, end) val queue = ArrayDeque().apply { add(Path(start)) } val visited = mutableMapOf, Long>() - val shortestPathPoints = mutableSetOf(end) + val shortestPathPoints = mutableSetOf(listOf(end)) while (queue.isNotEmpty()) { val path = queue.removeFirst() if (path.score > minScore) continue @@ -54,7 +72,7 @@ class Day16( if (key in visited && visited[key]!! < path.score) continue visited[key] = path.score if (path.position == end && path.score == minScore) { - shortestPathPoints.addAll(path.path) + shortestPathPoints.add(path.path) continue } @@ -70,9 +88,9 @@ class Day16( return shortestPathPoints } - fun part1() = shortestPathScore() + fun part1() = getScoreOfShortestPath(start, end) - fun part2() = pointsForShortestPaths().count() + fun part2() = getShortestPaths(start, end).flatMapTo(mutableSetOf()) { it }.count() } fun day16() {