-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathy23day11part1.kt
23 lines (22 loc) · 963 Bytes
/
y23day11part1.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import kotlin.math.abs
fun main() {
val input = generateSequence { readlnOrNull() }.toList()
val emptyRows = input.indices.filter { i -> input[i].all { it == '.' } }.toSet()
val emptyCols = input[0].indices.filter { j -> input.all { it[j] == '.' } }.toSet()
data class Pos(val i: Int, val j: Int)
val galaxies = buildList {
var extraRows = 0
input.forEachIndexed { i, row ->
if (i in emptyRows) ++extraRows
var extraCols = 0
row.forEachIndexed { j, c ->
if (j in emptyCols) ++extraCols
if (c == '#') add(Pos(i + extraRows, j + extraCols))
}
}
}
fun <T> Sequence<T>.pairs(): Sequence<Pair<T, T>> =
flatMapIndexed { i, a -> drop(i + 1).map { b -> Pair(a, b) } }
infix fun Pos.distanceTo(that: Pos) = abs(that.i - i) + abs(that.j - j)
galaxies.asSequence().pairs().sumOf { (a, b) -> a distanceTo b }.let(::println)
}