day(03): solve

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-03 09:46:35 +01:00
parent 1613941d96
commit cd852b0fbc
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8
3 changed files with 88 additions and 0 deletions

1
inputs/day03/sample.txt Normal file
View file

@ -0,0 +1 @@
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))

1
inputs/day03/sample2.txt Normal file
View file

@ -0,0 +1 @@
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

86
src/Day03.kt Normal file
View file

@ -0,0 +1,86 @@
class Day03(
inputType: String,
) : Day<Int, Int>() {
enum class InstructionType {
Do,
Dont,
Mul,
}
data class Instruction(
val type: InstructionType,
val value: Int,
)
companion object {
private val MUL_REGEX = "mul\\((\\d+),(\\d+)\\)".toRegex()
private val OP_REGEX = "(mul\\((\\d+),(\\d+)\\)|do\\(\\)|don't\\(\\))".toRegex()
}
private val memory: String = readInputAsString(3, inputType)
private var multiplications: List<Pair<Int, Int>> = listOf()
private var allInstructions: List<Instruction> = listOf()
override fun precompute() {
multiplications =
MUL_REGEX
.findAll(memory)
.map {
val (x, y) = it.destructured
x.toInt() to y.toInt()
}.toList()
allInstructions =
OP_REGEX
.findAll(memory)
.map {
val (op, l, r) = it.destructured
val type =
when {
op.startsWith("mul") -> InstructionType.Mul
op.startsWith("don't") -> InstructionType.Dont
op.startsWith("do") -> InstructionType.Do
else -> error("cannot have other operation")
}
val value =
when (type) {
InstructionType.Mul -> l.toInt() * r.toInt()
else -> 0
}
Instruction(type, value)
}.toList()
}
override fun part1(): Int = multiplications.sumOf { it.first * it.second }
override fun part2(): Int =
allInstructions
.fold(true to 0) { (running, sum), instr ->
var (running, sum) = running to sum
when (instr.type) {
InstructionType.Do -> {
running = true
}
InstructionType.Dont -> {
running = false
}
InstructionType.Mul -> {
if (running) {
sum += instr.value
}
}
}
running to sum
}.second
}
fun main() {
Day03("sample").test(161)
Day03("sample2").test(null, 48)
Day03("input").run()
}