Day 3.
This commit is contained in:
parent
1a9b08226a
commit
cc8abea2c4
2 changed files with 30 additions and 3 deletions
|
@ -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()
|
||||
|
|
|
@ -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")
|
||||
}
|
Loading…
Add table
Reference in a new issue