Advertisement
Guest User

Untitled

a guest
Dec 23rd, 2023
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.21 KB | Source Code | 0 0
  1. package Y2023.D23
  2.  
  3. class TheLongHike(map: List<String>) {
  4.     private val hikingTrails = map.mapIndexed { y, line ->
  5.         line.mapIndexed { x, spot -> (x to y) to spot }
  6.     }.flatten().toMap()
  7.     private val crossRoads = hikingTrails.filter {
  8.         it.value != '#' &&
  9.                 it.key.neighbours.filter(this::isValidPath).size != 2
  10.     }
  11.     private val trails = crossRoads.map { crossRoad ->
  12.         crossRoad.key.neighbours.filter(this::isValidPath)
  13.             .map { trail ->
  14.                 var count = 0
  15.                 var currentStep = trail
  16.                 var previousStep = crossRoad.key
  17.                 while (currentStep.neighbours.filter(this::isValidPath).size == 2) {
  18.                     val nextStep = currentStep.neighbours.filter(this::isValidPath).filter { it != previousStep }[0]
  19.                     previousStep = currentStep
  20.                     currentStep = nextStep
  21.                     count++
  22.                 }
  23.                 (crossRoad.key to currentStep) to count + 1
  24.             }
  25.     }.flatten().toMap()
  26.  
  27.     private fun isValidPath(neighbour: Pair<Int, Int>) =
  28.         hikingTrails[neighbour] != null && hikingTrails[neighbour] != '#'
  29.  
  30.     val start = map.first().indexOf('.') to 0
  31.     val end = map.last().indexOf('.') to map.lastIndex
  32.  
  33.     fun takeTheLongPath(): Int {
  34.         return hikingTheLongPath(start, emptyList(), 0)
  35.     }
  36.  
  37.     private fun hikingTheLongPath(
  38.         position: Pair<Int, Int>,
  39.         visited: List<Pair<Int, Int>>,
  40.         steps: Int
  41.     ): Int {
  42.         if (position == end) return steps
  43.         if (visited.contains(position)) return -1
  44.         val possibleTrails = trails.filter { it.key.first == position }
  45.         return possibleTrails.map { trail ->
  46.             hikingTheLongPath(trail.key.second, visited + trail.key.first, steps + trail.value)
  47.         }.max()!!
  48.     }
  49. }
  50.  
  51. private val <A, B> Pair<A, B>.reversed: Pair<B, A>
  52.     get() = this.second to this.first
  53.  
  54. private val Pair<Int, Int>.neighbours: Set<Pair<Int, Int>>
  55.     get() =
  56.         setOf(
  57.             this.first to this.second - 1,
  58.             this.first - 1 to this.second,
  59.             this.first + 1 to this.second,
  60.             this.first to this.second + 1
  61.         )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement