Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Y2024.D10
- class TrailHead(lines: List<String>) {
- private val startPositions = mutableListOf<Pair<Int, Int>>()
- private val trailMap = mutableMapOf<Pair<Int, Int>, Int>()
- init {
- lines.forEachIndexed { y, line ->
- line.forEachIndexed { x, tile ->
- if (tile == '0') startPositions.add(y to x)
- trailMap[y to x] = tile.digitToInt()
- }
- }
- }
- fun sumOfTrails(): Int {
- val alreadyWalked = mapOf<Pair<Int, Int>, Int>()
- return startPositions.sumOf { pos ->
- walkTheTrail(pos, 0).size
- }
- }
- fun walkTheTrail(pos: Pair<Int, Int>, height: Int): List<Pair<Int,Int>> {
- if (height == 9) return listOf(pos)
- val possibleSteps = trailMap.findNeighbours(pos).filter { it.second == height + 1 }
- if (possibleSteps.isEmpty()) return emptyList()
- return possibleSteps.map { walkTheTrail(it.first, height + 1) }.flatten()
- }
- private fun Map<Pair<Int, Int>, Int>.findNeighbours(pos: Pair<Int, Int>): List<Pair<Pair<Int, Int>, Int>> {
- return listOf<Pair<Pair<Int, Int>, Int>>() +
- trailMap.neighbourAt(pos + (-1 to 0)) +
- trailMap.neighbourAt(pos + (1 to 0)) +
- trailMap.neighbourAt(pos + (0 to -1)) +
- trailMap.neighbourAt(pos + (0 to 1))
- }
- }
- private fun MutableMap<Pair<Int, Int>, Int>.neighbourAt(pos: Pair<Int, Int>): Pair<Pair<Int, Int>, Int> {
- return pos to (this[pos] ?: -1)
- }
- private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
- return first + other.first to second + other.second
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement