Day 5 Part 2
This commit is contained in:
parent
3d02cb5d0b
commit
5de9f74342
1 changed files with 21 additions and 1 deletions
|
@ -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<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()) {
|
||||
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<Page>()
|
||||
}
|
Loading…
Add table
Reference in a new issue