From 7341109f4dca864dd67cb7c15c5fc9de9661cd2d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 2 Dec 2024 16:08:12 +0100 Subject: [PATCH] day(02): solve Signed-off-by: Matej Focko --- inputs/day02/sample.txt | 6 ++++++ src/Day02.kt | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 inputs/day02/sample.txt create mode 100644 src/Day02.kt diff --git a/inputs/day02/sample.txt b/inputs/day02/sample.txt new file mode 100644 index 0000000..82cd679 --- /dev/null +++ b/inputs/day02/sample.txt @@ -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 \ No newline at end of file diff --git a/src/Day02.kt b/src/Day02.kt new file mode 100644 index 0000000..a284291 --- /dev/null +++ b/src/Day02.kt @@ -0,0 +1,34 @@ +class Day02( + inputType: String, +) : Day() { + private val reports: List> = + readInput(2, inputType) + .map { line -> + line.split(" ").map { it.toInt() } + }.toList() + + override fun precompute() { + // [TODO] Implement precomputation + } + + private fun isCorrect(report: List): 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() +}