Advertisement
Guest User

AOC - 2024 day 10

a guest
Dec 10th, 2024
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.66 KB | None | 0 0
  1. package Y2024.D10
  2.  
  3. class TrailHead(lines: List<String>) {
  4.     private val startPositions = mutableListOf<Pair<Int, Int>>()
  5.     private val trailMap = mutableMapOf<Pair<Int, Int>, Int>()
  6.  
  7.     init {
  8.         lines.forEachIndexed { y, line ->
  9.             line.forEachIndexed { x, tile ->
  10.                 if (tile == '0') startPositions.add(y to x)
  11.                 trailMap[y to x] = tile.digitToInt()
  12.             }
  13.         }
  14.     }
  15.  
  16.     fun sumOfTrails(): Int {
  17.         val alreadyWalked = mapOf<Pair<Int, Int>, Int>()
  18.         return startPositions.sumOf { pos ->
  19.             walkTheTrail(pos, 0).size
  20.         }
  21.     }
  22.  
  23.     fun walkTheTrail(pos: Pair<Int, Int>, height: Int): List<Pair<Int,Int>> {
  24.         if (height == 9) return listOf(pos)
  25.         val possibleSteps = trailMap.findNeighbours(pos).filter { it.second == height + 1 }
  26.         if (possibleSteps.isEmpty()) return emptyList()
  27.         return possibleSteps.map { walkTheTrail(it.first, height + 1) }.flatten()
  28.     }
  29.  
  30.     private fun Map<Pair<Int, Int>, Int>.findNeighbours(pos: Pair<Int, Int>): List<Pair<Pair<Int, Int>, Int>> {
  31.         return listOf<Pair<Pair<Int, Int>, Int>>() +
  32.                 trailMap.neighbourAt(pos + (-1 to 0)) +
  33.                 trailMap.neighbourAt(pos + (1 to 0)) +
  34.                 trailMap.neighbourAt(pos + (0 to -1)) +
  35.                 trailMap.neighbourAt(pos + (0 to 1))
  36.  
  37.     }
  38. }
  39.  
  40. private fun MutableMap<Pair<Int, Int>, Int>.neighbourAt(pos: Pair<Int, Int>): Pair<Pair<Int, Int>, Int> {
  41.     return pos to (this[pos] ?: -1)
  42. }
  43.  
  44. private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> {
  45.     return first + other.first to second + other.second
  46. }
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement