day(05): solve part 1
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
2d68999fda
commit
9dd5ae0c39
2 changed files with 73 additions and 0 deletions
28
inputs/day05/sample.txt
Normal file
28
inputs/day05/sample.txt
Normal file
|
@ -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
|
45
src/Day05.kt
Normal file
45
src/Day05.kt
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
class Day05(
|
||||||
|
inputType: String,
|
||||||
|
) : Day<Int, Int>() {
|
||||||
|
private val rules: Map<Int, MutableSet<Int>>
|
||||||
|
private val updates: List<List<Int>>
|
||||||
|
|
||||||
|
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<Int>): 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<Int>): List<Int> = 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()
|
||||||
|
}
|
Loading…
Reference in a new issue