day03
This commit is contained in:
52
app/src/main/kotlin/day03/Day03.kt
Normal file
52
app/src/main/kotlin/day03/Day03.kt
Normal file
@@ -0,0 +1,52 @@
|
||||
|
||||
package day03
|
||||
|
||||
import kotlin.io.println
|
||||
|
||||
class Day03 {
|
||||
fun parse(input: String): String {
|
||||
throw NotImplementedError()
|
||||
}
|
||||
|
||||
fun part1(input: String): Int {
|
||||
val regex = Regex("mul\\((\\d{1,3}),(\\d{1,3})\\)")
|
||||
val muls = regex.findAll(input)
|
||||
|
||||
val product = muls.map { match ->
|
||||
match.groupValues.subList(1, match.groupValues.count())
|
||||
.map { it.toInt() }
|
||||
.toList()
|
||||
.reduce { acc, next -> acc * next }
|
||||
}
|
||||
.toList()
|
||||
.sum()
|
||||
|
||||
return product
|
||||
}
|
||||
|
||||
fun part2(input: String): Int {
|
||||
val regex = Regex("(?:mul\\((\\d{1,3}),(\\d{1,3})\\))|(do(?:n't)?\\(\\))")
|
||||
val muls = regex.findAll(input)
|
||||
var enable = true
|
||||
|
||||
val product = muls.map { match ->
|
||||
var tmp = 0
|
||||
if (match.value == "do()") {
|
||||
enable = true
|
||||
} else if (match.value == "don't()") {
|
||||
enable = false
|
||||
} else if (enable) {
|
||||
tmp = match.groupValues.subList(1, 3)
|
||||
.map { it.toInt() }
|
||||
.toList()
|
||||
.reduce { acc, next -> acc * next }
|
||||
}
|
||||
tmp
|
||||
}
|
||||
.toList()
|
||||
.sum()
|
||||
|
||||
return product
|
||||
|
||||
}
|
||||
}
|
42
app/src/test/kotlin/day03/Day03Test.kt
Normal file
42
app/src/test/kotlin/day03/Day03Test.kt
Normal file
@@ -0,0 +1,42 @@
|
||||
|
||||
package day03
|
||||
|
||||
import kotlin.test.Test
|
||||
import util.InputDownloader
|
||||
|
||||
class Day03Test {
|
||||
val dayNum = 3
|
||||
val day = Day03()
|
||||
|
||||
val input = InputDownloader().getInput(dayNum)
|
||||
val example = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
|
||||
val example2 = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
|
||||
|
||||
@Test fun part1Example() {
|
||||
part1(example, 161)
|
||||
}
|
||||
|
||||
@Test fun part1Solution() {
|
||||
part1(input, 153469856)
|
||||
}
|
||||
|
||||
@Test fun part2Example() {
|
||||
part2(example2, 48)
|
||||
}
|
||||
|
||||
@Test fun part2Solution() {
|
||||
part2(input, 77055967)
|
||||
}
|
||||
|
||||
fun part1(input: String, expected: Int) {
|
||||
val output = day.part1(input)
|
||||
println("output: $output")
|
||||
assert(output == expected)
|
||||
}
|
||||
|
||||
fun part2(input: String, expected: Int) {
|
||||
val output = day.part2(input)
|
||||
println("output: $output")
|
||||
assert(output == expected)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user