From cc8abea2c4954b09344a5b3989ddd66862c30321 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Tue, 3 Dec 2024 18:55:52 +0100 Subject: [PATCH] Day 3. --- 2024/src/main/kotlin/Utils.kt | 8 ++++++-- 2024/src/main/kotlin/day3.kt | 25 ++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/2024/src/main/kotlin/Utils.kt b/2024/src/main/kotlin/Utils.kt index 8183282..232ead7 100644 --- a/2024/src/main/kotlin/Utils.kt +++ b/2024/src/main/kotlin/Utils.kt @@ -1,4 +1,8 @@ -fun readInput(name: String) = object {}.javaClass.getResourceAsStream(name) - ?.bufferedReader() +fun readInput(name: String) = bufferedReader(name) ?.lineSequence() ?: error("Cannot read input") + +fun readInputString(name: String): String = bufferedReader(name)?.readText() ?: error("Cannot read input") + +private fun bufferedReader(name: String) = object {}.javaClass.getResourceAsStream(name) + ?.bufferedReader() diff --git a/2024/src/main/kotlin/day3.kt b/2024/src/main/kotlin/day3.kt index a104310..7b2af65 100644 --- a/2024/src/main/kotlin/day3.kt +++ b/2024/src/main/kotlin/day3.kt @@ -1,3 +1,26 @@ fun main() { - + val input = readInputString("day3.txt") + val regexPart1 = "mul\\((\\d+),(\\d+)\\)".toRegex() + + val part1 = regexPart1.findAll(input).fold(0) { acc, result -> + val (a, b) = result.destructured + acc + a.toInt() * b.toInt() + } + + println("Part 1: $part1") + + val regexPart2 = "do\\(\\)|don't\\(\\)|mul\\((\\d+),(\\d+)\\)".toRegex() + var enabled = true + var part2 = 0 + for (command in regexPart2.findAll(input)) { + when (command.value) { + "do()" -> enabled = true + "don't()" -> enabled = false + else -> if (enabled) { + val (a, b) = command.destructured + part2 += a.toInt() * b.toInt() + } + } + } + println("Part 2: $part2") } \ No newline at end of file