Skip to content

Commit 6fccf80

Browse files
committed
Solved day11 part 1
1 parent 0288fc0 commit 6fccf80

File tree

1 file changed

+65
-1
lines changed
  • day11/src/main/kotlin/de/havox_design/aoc2023/day11

1 file changed

+65
-1
lines changed
Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,76 @@
11
package de.havox_design.aoc2023.day11
22

3+
import kotlin.math.abs
4+
35
class Day11(private var filename: String) {
6+
private val ICON_GALAXY = "#"
7+
48
fun solvePart1(): Long =
5-
374L
9+
processSumOfAllDistances(getResourceAsText(filename))
610

711
fun solvePart2(): Long =
812
0L
913

14+
private fun processSumOfAllDistances(input: List<String>): Long {
15+
val galaxies = input
16+
.flatMapIndexed { y, s ->
17+
s.mapIndexed { x, c -> if (c == ICON_GALAXY.first()) Pair(y.toLong(), x.toLong()) else null }
18+
}
19+
.filterNotNull()
20+
val emptyRows = input
21+
.withIndex()
22+
.filter { !it.value.contains(ICON_GALAXY) }
23+
.map { it.index.toLong() }
24+
val emptyColumns = input
25+
.map { it.toList() }
26+
.transpose()
27+
.withIndex()
28+
.filter {
29+
!it
30+
.value
31+
.joinToString("") { c -> c.toString() }
32+
.contains(ICON_GALAXY)
33+
}
34+
.map { it.index.toLong() }
35+
val expandedGalaxies = calculateUniverseExpansion(galaxies, emptyRows, emptyColumns)
36+
val galaxyPairs = expandedGalaxies
37+
.flatMapIndexed { index, galaxy ->
38+
expandedGalaxies
39+
.drop(index + 1)
40+
.map { Pair(galaxy, it) }
41+
}
42+
val distances = galaxyPairs
43+
.map { calculateDistance(it.first, it.second) }
44+
45+
return distances.sumOf { it }
46+
}
47+
48+
private fun calculateUniverseExpansion(
49+
galaxies: List<Pair<Long, Long>>,
50+
emptyRows: List<Long>,
51+
emptyColumns: List<Long>
52+
) =
53+
galaxies
54+
.map {
55+
Pair(it.first + emptyRows.count { r -> r < it.first },
56+
it.second + emptyColumns.count { c -> c < it.second })
57+
}
58+
59+
private fun calculateDistance(galaxy1: Pair<Long, Long>, galaxy2: Pair<Long, Long>): Long {
60+
return abs(galaxy2.first - galaxy1.first) + abs(galaxy2.second - galaxy1.second)
61+
}
62+
63+
private fun <T> List<List<T>>.transpose(): List<List<T>> {
64+
return when {
65+
this.isEmpty() -> this
66+
else -> (this[0].indices)
67+
.map { i ->
68+
(this.indices)
69+
.map { j -> this[j][i] }
70+
}
71+
}
72+
}
73+
1074
private fun getResourceAsText(path: String): List<String> =
1175
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
1276
}

0 commit comments

Comments
 (0)