Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Galaxies(galaxymap: List<String>, expansion: Long = 2) {
- private val galaxies: List<Pair<Long, Long>>
- init {
- val additionalExpansion = expansion - 1 // Minus the existing empty line
- var galaxies: List<Pair<Long, Long>> = galaxymap.mapIndexed { y, line ->
- line.mapIndexed { x, point -> if (point == '#') x.toLong() to y.toLong() else null }.filterNotNull()
- }.flatten()
- var shiftY = 0L
- galaxymap.indices.forEach { y ->
- if (galaxies.none { it.second == y + shiftY }) {
- val yPos = y + shiftY
- shiftY += additionalExpansion
- galaxies = galaxies.map {
- if (it.second > yPos) (it.first to it.second + additionalExpansion) else it
- }
- }
- }
- var shiftX = 0L
- galaxymap[0].indices.forEach { x ->
- if (galaxies.none { it.first == x + shiftX }) {
- val xPos = x + shiftX
- shiftX += additionalExpansion
- galaxies = galaxies.map {
- if (it.first > xPos) (it.first + additionalExpansion) to it.second else it
- }
- }
- }
- this.galaxies = galaxies
- }
- fun shortestDistancesBetweenGalaxies(): Long {
- return galaxies.indices.map { index ->
- val current = galaxies[index]
- galaxies.subList(index + 1, galaxies.size).map { other ->
- abs(current.first - other.first) + abs(current.second - other.second)
- }.sum()
- }.sum()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement