Advertisement
Guest User

Untitled

a guest
Dec 11th, 2023
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.75 KB | Source Code | 0 0
  1.  
  2.     class Galaxies(galaxymap: List<String>, expansion: Long = 2) {
  3.         private val galaxies: List<Pair<Long, Long>>
  4.         init {
  5.             val additionalExpansion = expansion - 1 // Minus the existing empty line
  6.             var galaxies: List<Pair<Long, Long>> = galaxymap.mapIndexed { y, line ->
  7.                 line.mapIndexed { x, point ->  if (point == '#') x.toLong() to y.toLong() else null }.filterNotNull()
  8.             }.flatten()
  9.    
  10.             var shiftY = 0L
  11.             galaxymap.indices.forEach { y ->
  12.                 if (galaxies.none { it.second == y + shiftY }) {
  13.                     val yPos = y + shiftY
  14.                     shiftY += additionalExpansion
  15.                     galaxies = galaxies.map {
  16.                         if (it.second > yPos) (it.first to it.second + additionalExpansion) else it
  17.                     }
  18.                 }
  19.             }
  20.             var shiftX = 0L
  21.             galaxymap[0].indices.forEach { x ->
  22.                 if (galaxies.none {  it.first == x + shiftX }) {
  23.                     val xPos = x + shiftX
  24.                     shiftX += additionalExpansion
  25.                     galaxies = galaxies.map {
  26.                         if (it.first > xPos) (it.first + additionalExpansion) to it.second else it
  27.                     }
  28.                 }
  29.             }
  30.             this.galaxies = galaxies
  31.         }
  32.    
  33.    
  34.         fun shortestDistancesBetweenGalaxies(): Long {
  35.             return galaxies.indices.map { index ->
  36.                 val current = galaxies[index]
  37.                 galaxies.subList(index + 1, galaxies.size).map { other ->
  38.                     abs(current.first - other.first) + abs(current.second - other.second)
  39.                 }.sum()
  40.             }.sum()
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement