diff --git a/inputs/day05/sample.txt b/inputs/day05/sample.txt new file mode 100644 index 0000000..d4d4441 --- /dev/null +++ b/inputs/day05/sample.txt @@ -0,0 +1,28 @@ +47|53 +97|13 +97|61 +97|47 +75|29 +61|13 +75|53 +29|13 +97|29 +53|29 +61|53 +97|53 +61|29 +47|13 +75|47 +97|75 +47|61 +75|61 +47|29 +75|13 +53|13 + +75,47,61,53,29 +97,61,53,29,13 +75,29,13 +75,97,47,61,53 +61,13,29 +97,13,75,29,47 \ No newline at end of file diff --git a/src/Day05.kt b/src/Day05.kt new file mode 100644 index 0000000..93c9d21 --- /dev/null +++ b/src/Day05.kt @@ -0,0 +1,45 @@ +class Day05( + inputType: String, +) : Day() { + private val rules: Map> + private val updates: List> + + companion object { + } + + init { + val (rules, updates) = readInputAsString(5, inputType).split("\n\n") + + this.rules = + buildMap { + rules + .lineSequence() + .map { line -> + line.split("|").map(String::toInt).let { it[0] to it[1] } + }.forEach { (before, after) -> + getOrPut(after) { mutableSetOf() }.add(before) + } + } + this.updates = updates.lineSequence().map { line -> line.split(",").map(String::toInt).toList() }.toList() + } + + override fun precompute() { + // no-op + } + + private fun isCorrect(update: List): Boolean = + update.withIndex().reversed().all { p -> + rules.getOrDefault(p.value, mutableSetOf()).all { preceding -> update.lastIndexOf(preceding) < p.index } + } + + override fun part1(): Int = updates.filter(::isCorrect).sumOf { it[it.size / 2] } + + private fun fix(update: List): List = update + + override fun part2(): Int = updates.filter { !isCorrect(it) }.map { fix(it) }.sumOf { it[it.size / 2] } +} + +fun main() { + Day05("sample").test(143, 123) + Day05("input").run() +}