Skip to content

Instantly share code, notes, and snippets.

@Valefant
Created December 11, 2023 09:15
Show Gist options
  • Save Valefant/8567597bd9fadf9637baf8785972cf00 to your computer and use it in GitHub Desktop.
Save Valefant/8567597bd9fadf9637baf8785972cf00 to your computer and use it in GitHub Desktop.
My solution in Kotlin
import java.io.File
import kotlin.math.abs
fun main() {
val data = File("src/main/kotlin/day11/input.txt").readLines()
val rowIndices = data.mapIndexedNotNull { i, row ->
if (row.all { it == '.' }) {
i
} else {
null
}
}
val columnIndices = data[0].indices.mapIndexedNotNull { i, _ ->
if (data.indices.map { j -> data[j][i] }.all { it == '.' }) {
i
} else {
null
}
}
expand(data, rowIndices, columnIndices, 2).let(::shortestPath).also { println("Part 1: $it") }
expand(data, rowIndices, columnIndices, 1_000_000).let(::shortestPath).also { println("Part 2: $it") }
}
fun shortestPath(coords: List<Coord>): Long {
return coords.mapIndexed { i, coord -> coords.subList(i + 1, coords.size).map { c -> CoordPair(coord, c) } }
.flatten()
.sumOf(CoordPair::distance)
}
data class Coord(val x: Long, val y: Long) {
fun distance(other: Coord) = abs(x - other.x) + abs(y - other.y)
}
data class CoordPair(val first: Coord, val second: Coord) {
fun distance() = first.distance(second)
}
fun expand(data: List<String>, rowIndices: List<Int>, columnIndices: List<Int>, distance: Int): List<Coord> {
val coords = mutableListOf<Coord>()
var rowOffset = 0L
data.forEachIndexed { i, row ->
if (i in rowIndices) {
rowOffset += (distance - 1)
}
var columnOffset = 0L
row.forEachIndexed { j, c ->
if (j in columnIndices) {
columnOffset += (distance - 1)
}
if (c == '#') {
coords += Coord(j + columnOffset, i + rowOffset)
}
}
}
return coords
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment