|
| 1 | +package y24 |
| 2 | + |
| 3 | +import common.puzzle.solvePuzzle |
| 4 | +import common.puzzle.Input |
| 5 | +import common.puzzle.Puzzle |
| 6 | +import common.datastructures.* |
| 7 | +import common.ext.* |
| 8 | +import common.puzzle.splitToInts |
| 9 | +import common.util.* |
| 10 | +import java.util.* |
| 11 | +import kotlin.math.* |
| 12 | +import kotlin.system.exitProcess |
| 13 | + |
| 14 | + |
| 15 | +fun main() = solvePuzzle(year = 2024, day = 5) { Day5(it) } |
| 16 | + |
| 17 | +class Day5(val input: Input) : Puzzle { |
| 18 | + |
| 19 | + data class PageRule( |
| 20 | + val before: Int, |
| 21 | + val after: Int, |
| 22 | + ) |
| 23 | + |
| 24 | + data class Update( |
| 25 | + val pageNumbers: List<Int>, |
| 26 | + ) { |
| 27 | + val middle = pageNumbers[pageNumbers.size / 2] |
| 28 | + |
| 29 | + fun satisfies(rules: List<PageRule>): Boolean { |
| 30 | + val pageIndices = pageNumbers.mapIndexed { index, i -> i to index }.toMap() |
| 31 | + return rules.all { (before, after) -> |
| 32 | + val beforeIndex = pageIndices[before] ?: return@all true |
| 33 | + val afterIndex = pageIndices[after] ?: return@all true |
| 34 | + beforeIndex < afterIndex |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + fun sortedBy(rules: List<PageRule>): Update { |
| 39 | + val sorted = pageNumbers.sortedWith(Comparator { p1, p2 -> |
| 40 | + val rule = rules.find { (it.before == p1 && it.after == p2) || (it.before == p2 && it.after == p1) } |
| 41 | + ?: return@Comparator 0 |
| 42 | + |
| 43 | + if (rule.before == p1) -1 else 1 |
| 44 | + }) |
| 45 | + |
| 46 | + return Update(sorted) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private val emptyLine = input.lines.indexOf("") |
| 51 | + private val rules = input.lines.subList(0, emptyLine).map { line -> |
| 52 | + val (before, after) = line.splitToInts("|") |
| 53 | + PageRule(before, after) |
| 54 | + } |
| 55 | + private val updates = input.lines.subList(emptyLine + 1, input.lines.size).map { line -> |
| 56 | + val pageNumbers = line.splitToInts(",") |
| 57 | + Update(pageNumbers) |
| 58 | + } |
| 59 | + |
| 60 | + override fun solveLevel1(): Any { |
| 61 | + return updates.filter { it.satisfies(rules) }.sumOf { it.middle } |
| 62 | + } |
| 63 | + override fun solveLevel2(): Any { |
| 64 | + return updates.filter { !it.satisfies(rules) }.map { it.sortedBy(rules) }.sumOf { it.middle } |
| 65 | + } |
| 66 | +} |
0 commit comments