day(03): refactor
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
cd852b0fbc
commit
f4854fa462
1 changed files with 28 additions and 34 deletions
62
src/Day03.kt
62
src/Day03.kt
|
@ -13,50 +13,44 @@ class Day03(
|
||||||
)
|
)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private val MUL_REGEX = "mul\\((\\d+),(\\d+)\\)".toRegex()
|
|
||||||
private val OP_REGEX = "(mul\\((\\d+),(\\d+)\\)|do\\(\\)|don't\\(\\))".toRegex()
|
private val OP_REGEX = "(mul\\((\\d+),(\\d+)\\)|do\\(\\)|don't\\(\\))".toRegex()
|
||||||
}
|
}
|
||||||
|
|
||||||
private val memory: String = readInputAsString(3, inputType)
|
private val instructions: List<Instruction> =
|
||||||
private var multiplications: List<Pair<Int, Int>> = listOf()
|
OP_REGEX
|
||||||
private var allInstructions: List<Instruction> = listOf()
|
.findAll(readInputAsString(3, inputType))
|
||||||
|
.map {
|
||||||
|
val (op, l, r) = it.destructured
|
||||||
|
|
||||||
override fun precompute() {
|
val type =
|
||||||
multiplications =
|
when {
|
||||||
MUL_REGEX
|
op.startsWith("mul") -> InstructionType.Mul
|
||||||
.findAll(memory)
|
op.startsWith("don't") -> InstructionType.Dont
|
||||||
.map {
|
op.startsWith("do") -> InstructionType.Do
|
||||||
val (x, y) = it.destructured
|
else -> error("cannot have other operation")
|
||||||
x.toInt() to y.toInt()
|
}
|
||||||
}.toList()
|
val value =
|
||||||
|
when (type) {
|
||||||
|
InstructionType.Mul -> l.toInt() * r.toInt()
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
|
||||||
allInstructions =
|
Instruction(type, value)
|
||||||
OP_REGEX
|
}.toList()
|
||||||
.findAll(memory)
|
|
||||||
.map {
|
|
||||||
val (op, l, r) = it.destructured
|
|
||||||
|
|
||||||
val type =
|
override fun precompute() { // no-op
|
||||||
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 part1(): Int =
|
||||||
|
instructions.sumOf {
|
||||||
|
when (it.type) {
|
||||||
|
InstructionType.Mul -> it.value
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun part2(): Int =
|
override fun part2(): Int =
|
||||||
allInstructions
|
instructions
|
||||||
.fold(true to 0) { (running, sum), instr ->
|
.fold(true to 0) { (running, sum), instr ->
|
||||||
var (running, sum) = running to sum
|
var (running, sum) = running to sum
|
||||||
when (instr.type) {
|
when (instr.type) {
|
||||||
|
|
Loading…
Reference in a new issue