diff --git a/src/Day01.kt b/src/Day01.kt index 644d3fd..1edadd1 100644 --- a/src/Day01.kt +++ b/src/Day01.kt @@ -33,11 +33,9 @@ fun main() { } } - val testInput1 = readInput("Day01_test_part1") - check(part1(testInput1) == 11L) - - val testInput2 = readInput("Day01_test_part2") - check(part2(testInput2) == 31L) + val testInput = readInput("Day01_test") + check(part1(testInput) == 11L) + check(part2(testInput) == 31L) val input = readInput("Day01") part1(input).println() diff --git a/src/Day02.kt b/src/Day02.kt index eeb3dcd..07c057d 100644 --- a/src/Day02.kt +++ b/src/Day02.kt @@ -58,11 +58,9 @@ fun main() { } } - val testInput1 = readInput("Day02_test_part1") - check(part1(testInput1) == 2) - - val testInput2 = readInput("Day02_test_part2") - check(part2(testInput2) == 4) + val testInput = readInput("Day02_test") + check(part1(testInput) == 2) + check(part2(testInput) == 4) val input = readInput("Day02") part1(input).println() diff --git a/src/Day03.kt b/src/Day03.kt new file mode 100644 index 0000000..dadecd7 --- /dev/null +++ b/src/Day03.kt @@ -0,0 +1,58 @@ +fun main() { + + data class Multiplication( + val a: Int, + val b: Int + ) { + constructor(a: String, b: String) : this(a.toInt(), b.toInt()) + + fun mul() = a * b + } + + fun String.extractEnabledMuls(): List { + val regex = Regex("mul\\((\\d{1,3}),(\\d{1,3})\\)|do\\(\\)|don't\\(\\)") + var isEnabled = true + return buildList { + regex.findAll(this@extractEnabledMuls).forEach { + val isDo = it.value == "do()" + val isDonot = it.value == "don't()" + when { + isDo -> isEnabled = true + isDonot -> isEnabled = false + else -> { + if (isEnabled) { + add(Multiplication(it.groups[1]!!.value, it.groups[2]!!.value)) + } + } + } + } + } + } + + fun String.extractMuls(): List { + val regex = Regex("mul\\((\\d{1,3}),(\\d{1,3})\\)") + return buildList { + regex.findAll(this@extractMuls).forEach { + add(Multiplication(it.groups[1]!!.value, it.groups[2]!!.value)) + } + } + } + + fun part1(input: List): Int { + val oneBigLine = input.joinToString(separator = "") + return oneBigLine.extractMuls().sumOf { it.mul() } + } + + fun part2(input: List): Int { + val oneBigLine = input.joinToString(separator = "") + return oneBigLine.extractEnabledMuls().sumOf { it.mul() } + } + + val testInput1 = readInput("Day03_test") + check(part1(testInput1) == 161) + check(part2(testInput1) == 48) + + val input = readInput("Day03") + part1(input).println() + part2(input).println() +}