This commit is contained in:
parent
a4264163af
commit
0a78452ca9
50
day05.kts
Executable file
50
day05.kts
Executable file
@ -0,0 +1,50 @@
|
|||||||
|
#!/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")
|
2
day05.kts.testvalue
Normal file
2
day05.kts.testvalue
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
Ordered middle sum: 5713
|
||||||
|
Unordered middle sum: 5180
|
1376
day05input.txt
Normal file
1376
day05input.txt
Normal file
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user