Day 5 Part 2

This commit is contained in:
Sven Weidauer 2024-12-08 13:17:03 +01:00
parent 3d02cb5d0b
commit 5de9f74342

View file

@ -4,12 +4,12 @@ fun main() {
var completedRules = false var completedRules = false
var part1 = 0 var part1 = 0
var part2 = 0
for (line in readInput("day5.txt")) { for (line in readInput("day5.txt")) {
if (completedRules) { if (completedRules) {
val job = line.split(",").map { it.toInt() } val job = line.split(",").map { it.toInt() }
assert(job.count() % 2 != 0) assert(job.count() % 2 != 0)
val middlePage = job[job.count() / 2]
var matches = true var matches = true
for ((first, second) in rules) { for ((first, second) in rules) {
@ -23,7 +23,23 @@ fun main() {
} }
if (matches) { if (matches) {
val middlePage = job[job.count() / 2]
part1 += middlePage part1 += middlePage
} else {
val usedRules = rules.filter { (first, second) -> job.contains(first) && job.contains(second) }
val pages = mutableMapOf<Int, Page>()
for (rule in usedRules) {
val first = pages.getOrPut(rule.first) { Page(rule.first) }
val second = pages.getOrPut(rule.second) { Page(rule.second) }
second.previous.add(first)
}
val orderedJob = pages.values.sortedBy { it.previous.count() }.map { it.number }
val middlePage = orderedJob[orderedJob.count() / 2]
part2 += middlePage
} }
} else if (line.isEmpty()) { } else if (line.isEmpty()) {
completedRules = true completedRules = true
@ -34,5 +50,9 @@ fun main() {
} }
println("Part 1: $part1") println("Part 1: $part1")
println("Part 2: $part2")
}
data class Page(val number: Int) {
val previous = mutableSetOf<Page>()
} }