From f1875986f3a208ce6b9bcf0004a9af65417c5c9d Mon Sep 17 00:00:00 2001 From: Paul Woitaschek Date: Tue, 10 Dec 2024 08:11:49 +0100 Subject: [PATCH] Clean up part 10 --- 2024/src/main/kotlin/aoc/year2024/Day10.kt | 49 ++++++++++------------ 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/2024/src/main/kotlin/aoc/year2024/Day10.kt b/2024/src/main/kotlin/aoc/year2024/Day10.kt index 084a55e..ee28e48 100644 --- a/2024/src/main/kotlin/aoc/year2024/Day10.kt +++ b/2024/src/main/kotlin/aoc/year2024/Day10.kt @@ -15,37 +15,32 @@ object Day10 : Puzzle(day = 10) { ): Int { val mountains = input.lines().flatMapIndexed { y, line -> line.mapIndexed { x, char -> - Point(x, y) to (char.digitToIntOrNull() ?: -1) + Point(x, y) to char.digitToIntOrNull() } }.toMap() - return mountains.toList() - .sumOf { (point, height) -> - if (height == 0) { - val reachedNines = mutableListOf() - fun visit( - currentHeight: Int, - point: Point, - ) { - val heightAtPoint = mountains[point] ?: return - if (heightAtPoint == currentHeight + 1) { - if (heightAtPoint == 9) { - reachedNines += point - } else { - point.adjacentOrthogonal().forEach { - visit(heightAtPoint, it) - } - } - } - } - visit(-1, point) - if (countUniqueTrails) { - reachedNines.toSet().size - } else { - reachedNines.size - } + + fun visit( + currentHeight: Int, + point: Point, + reachedNines: MutableList, + ) { + val heightAtPoint = mountains[point] ?: return + if (heightAtPoint == currentHeight + 1) { + if (heightAtPoint == 9) { + reachedNines += point } else { - 0 + point.adjacentOrthogonal().forEach { adjacent -> + visit(heightAtPoint, adjacent, reachedNines) + } } } + } + return mountains.toList() + .filter { (_, height) -> height == 0 } + .sumOf { (start, _) -> + val reachedNines = mutableListOf() + visit(-1, start, reachedNines) + if (countUniqueTrails) reachedNines.toSet().size else reachedNines.size + } } }