Skip to content

Commit 70153b4

Browse files
committed
Day 3
1 parent 3a2b2ed commit 70153b4

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

src/main/kotlin/y24/Day3.kt

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package y24
2+
3+
import common.puzzle.solvePuzzle
4+
import common.puzzle.Input
5+
import common.puzzle.Puzzle
6+
7+
fun main() = solvePuzzle(year = 2024, day = 3) { Day3(it) }
8+
9+
class Day3(val input: Input) : Puzzle {
10+
private val mulRegex = Regex("""mul\((\d+),(\d+)\)""")
11+
12+
override fun solveLevel1(): Any {
13+
return mulRegex.findAll(input.string).sumOf {
14+
it.groupValues[1].toLong() * it.groupValues[2].toLong()
15+
}
16+
}
17+
18+
override fun solveLevel2(): Any {
19+
val memory = disableMul(input.string)
20+
return mulRegex.findAll(memory).sumOf {
21+
it.groupValues[1].toLong() * it.groupValues[2].toLong()
22+
}
23+
}
24+
25+
fun disableMul(input: String): String {
26+
val result = input.toCharArray()
27+
28+
var i = 0
29+
while (i < input.length) {
30+
val nextDont = input.indexOf("don't()", i)
31+
if (nextDont == -1) {
32+
return result.joinToString("")
33+
}
34+
35+
val nextDo = input.indexOf("do()", nextDont)
36+
if (nextDo == -1) {
37+
// Clear until end of string.
38+
result.fill(' ', nextDont, input.length)
39+
return result.joinToString("")
40+
}
41+
42+
result.fill(' ', nextDont, nextDo)
43+
i = nextDo
44+
}
45+
46+
return result.joinToString("")
47+
}
48+
}

src/test/kotlin/y24/Day3Test.kt

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package y24
2+
3+
import common.puzzle.Input
4+
import org.junit.jupiter.api.Assertions.assertEquals
5+
import org.junit.jupiter.api.Test
6+
7+
internal class Day3Test {
8+
private val sample = Input("""
9+
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
10+
""".trimIndent())
11+
12+
private val day = Day3(sample)
13+
14+
@Test
15+
fun solveLevel1() {
16+
assertEquals(161L, day.solveLevel1())
17+
}
18+
19+
@Test
20+
fun solveLevel2() {
21+
assertEquals(48L, Day3(Input("xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))")).solveLevel2())
22+
}
23+
}

0 commit comments

Comments
 (0)