50 lines
1.5 KiB
Kotlin
Executable File
50 lines
1.5 KiB
Kotlin
Executable File
#!/usr/bin/env kotlin
|
|
import java.io.File
|
|
import java.util.Scanner
|
|
|
|
var orderingRules = mutableListOf<Pair<Int, Int>>()
|
|
var pagesList = mutableListOf<MutableList<Int>>()
|
|
val scanner = Scanner(File("day05input.txt"))
|
|
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 {
|
|
val orderedPage = page.sortedWith(Comparator { a, b -> compareByRules(a, b) })
|
|
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") |