day(02): solve

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-02 16:08:12 +01:00
parent 273204ca6b
commit 7341109f4d
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8
2 changed files with 40 additions and 0 deletions

6
inputs/day02/sample.txt Normal file
View file

@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9

34
src/Day02.kt Normal file
View file

@ -0,0 +1,34 @@
class Day02(
inputType: String,
) : Day<Int, Int>() {
private val reports: List<List<Int>> =
readInput(2, inputType)
.map { line ->
line.split(" ").map { it.toInt() }
}.toList()
override fun precompute() {
// [TODO] Implement precomputation
}
private fun isCorrect(report: List<Int>): Boolean {
val isIncreasing = report[0] < report[1]
return report.windowed(2).fold(true) { acc, (x, y) ->
acc && maxOf(x - y, y - x) in 1..3 && ((isIncreasing && x < y) || (!isIncreasing && x > y))
}
}
override fun part1(): Int = reports.count(::isCorrect)
override fun part2(): Int =
reports.count { report ->
report.indices.any { skip ->
isCorrect(report.filterIndexed { idx, _ -> idx != skip })
}
}
}
fun main() {
Day02("sample").test(2, 4)
Day02("input").run()
}