Skip to content

Commit 70b7f27

Browse files
committed
Optimize KeypadConundrum for performance
But it still consumes too much memory for part two of day 21. Since we don't need the actual input sequence at all, we might just calculate its length.
1 parent ce1648d commit 70b7f27

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

src/main/kotlin/de/ronny_h/aoc/year24/day21/KeypadConundrum.kt

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,40 @@ import de.ronny_h.aoc.extensions.Direction
55
import de.ronny_h.aoc.extensions.Direction.*
66
import de.ronny_h.aoc.extensions.SimpleCharGrid
77
import de.ronny_h.aoc.extensions.asList
8+
import de.ronny_h.aoc.extensions.memoize
89

910
fun main() = KeypadConundrum().run(94426, 0)
1011

1112
class KeypadConundrum : AdventOfCode<Int>(2024, 21) {
1213
fun input(code: String, keypad: Keypad, depth: Int): String {
13-
if (depth == 0) {
14-
return code
15-
}
14+
data class Parameters(val code: String, val depth: Int)
15+
16+
val keypads = buildList(depth) {
17+
repeat(depth) { add(Keypad(directionalKeypadLayout)) }
18+
} + keypad
19+
lateinit var inputRec: (Parameters) -> String
20+
21+
inputRec = { p: Parameters ->
22+
if (p.depth == 0) {
23+
p.code
24+
} else {
25+
p.code.map { char ->
26+
keypads[p.depth].moveTo(char).map {
27+
inputRec(Parameters(it, p.depth - 1))
28+
}.minBy { it.length }
29+
}.joinToString("")
30+
}
31+
}.memoize()
1632

17-
return code.map { char ->
18-
keypad.moveTo(char).map {
19-
input(it, Keypad(directionalKeypadLayout), depth - 1)
20-
}.minBy { it.length }
21-
}.joinToString("")
33+
return inputRec(Parameters(code, depth))
2234
}
2335

2436
override fun part1(input: List<String>): Int = input.sumOf {
2537
input(it, Keypad(numericKeypadLayout), 3).length * it.dropLast(1).toInt()
2638
}
2739

28-
override fun part2(input: List<String>): Int {
29-
TODO("Not yet implemented")
40+
override fun part2(input: List<String>): Int = input.sumOf {
41+
input(it, Keypad(numericKeypadLayout), 26).length * it.dropLast(1).toInt()
3042
}
3143
}
3244

0 commit comments

Comments
 (0)