day(03): refactor

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-12-03 09:50:18 +01:00
parent cd852b0fbc
commit f4854fa462
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -13,26 +13,12 @@ class Day03(
)
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 =
private val instructions: List<Instruction> =
OP_REGEX
.findAll(memory)
.findAll(readInputAsString(3, inputType))
.map {
val (op, l, r) = it.destructured
@ -51,12 +37,20 @@ class Day03(
Instruction(type, value)
}.toList()
override fun precompute() { // no-op
}
override fun part1(): Int = multiplications.sumOf { it.first * it.second }
override fun part1(): Int =
instructions.sumOf {
when (it.type) {
InstructionType.Mul -> it.value
else -> 0
}
}
override fun part2(): Int =
allInstructions
instructions
.fold(true to 0) { (running, sum), instr ->
var (running, sum) = running to sum
when (instr.type) {