aoc_2024/day05.kts

49 lines
1.5 KiB
Plaintext
Raw Normal View History

2024-12-05 06:55:38 +00:00
#!/usr/bin/env kotlin
import java.util.Scanner
var orderingRules = mutableListOf<Pair<Int, Int>>()
var pagesList = mutableListOf<MutableList<Int>>()
2024-12-05 13:43:19 +00:00
val scanner = Scanner(System.`in`)
2024-12-05 06:55:38 +00:00
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
if (line.contains('|')) {
val order = line.split("|").map { it.toInt() }
orderingRules.add(Pair(order[0], order[1]))
} else if (line.contains(',')) {
val pages = line.split(",").map { it.toInt() }
pagesList.add(pages.toMutableList())
}
}
var orderedMiddleSum = 0
var unorderedMiddleSum = 0
for (page in pagesList) {
if (isOrdered(page)) {
orderedMiddleSum += page[page.size / 2]
} else {
2024-12-05 07:14:31 +00:00
val orderedPage = page.sortedWith { a, b -> compareByRules(a, b) }
2024-12-05 06:55:38 +00:00
unorderedMiddleSum += orderedPage[orderedPage.size / 2]
}
}
fun compareByRules(a: Int, b: Int): Int {
for ((smaller, bigger) in orderingRules) {
if (a == smaller && b == bigger) return -1
if (a == bigger && b == smaller) return 1
}
return 0
}
fun isOrdered(page: MutableList<Int>): Boolean {
for (i in orderingRules.indices) {
val (smaller, bigger) = orderingRules[i]
val smallerIndex = page.indexOf(smaller)
val biggerIndex = page.indexOf(bigger)
if (smallerIndex != -1 && biggerIndex != -1 && biggerIndex < smallerIndex) {
return false
}
}
return true
}
println("Ordered middle sum: $orderedMiddleSum")
println("Unordered middle sum: $unorderedMiddleSum")