advent-of-code-2024/05-b.kts

31 lines
774 B
Text
Raw Permalink Normal View History

2024-12-05 15:27:31 +08:00
import java.util.Scanner
val scanner = Scanner(System.`in`)
val rules = HashMap<Int, MutableSet<Int>>()
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
if (line == "") {
break;
}
val (before, after) = line.split("|").map(String::toInt)
if (!rules.contains(before)) {
rules[before] = HashSet<Int>()
}
rules[before]!!.add(after)
}
var sum = 0
while (scanner.hasNextLine()) {
val line = scanner.nextLine()
val pages = line.split(",").map(String::toInt)
val fixed = pages.sortedWith { l, r -> if (l == r) 0 else if (rules[l]?.contains(r) == true) -1 else 1 }
if ("$pages" != "$fixed") {
val fixedArray = fixed.toIntArray()
sum += fixedArray[fixedArray.size / 2]
}
}
println(sum)