diff --git a/2024/src/main/kotlin/day5.kt b/2024/src/main/kotlin/day5.kt index ceabfe1..a15df87 100644 --- a/2024/src/main/kotlin/day5.kt +++ b/2024/src/main/kotlin/day5.kt @@ -4,12 +4,12 @@ fun main() { var completedRules = false var part1 = 0 + var part2 = 0 for (line in readInput("day5.txt")) { if (completedRules) { val job = line.split(",").map { it.toInt() } assert(job.count() % 2 != 0) - val middlePage = job[job.count() / 2] var matches = true for ((first, second) in rules) { @@ -23,7 +23,23 @@ fun main() { } if (matches) { + val middlePage = job[job.count() / 2] part1 += middlePage + } else { + val usedRules = rules.filter { (first, second) -> job.contains(first) && job.contains(second) } + + val pages = mutableMapOf() + 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()) { completedRules = true @@ -34,5 +50,9 @@ fun main() { } println("Part 1: $part1") + println("Part 2: $part2") +} +data class Page(val number: Int) { + val previous = mutableSetOf() } \ No newline at end of file