@@ -25,6 +25,14 @@ object Day21 : DayOf2024(21) {
25
25
""" .trimIndent().lines().map { it.toList() }
26
26
27
27
override fun first (): Any? {
28
+ return solve(2 )
29
+ }
30
+
31
+ override fun second (): Any? {
32
+ return solve(25 )
33
+ }
34
+
35
+ private fun solve (robots : Int ): Long {
28
36
val digitsMap = digits.flatMapIndexed { y, row ->
29
37
row.mapIndexedNotNull { x, c ->
30
38
if (c != ' ' ) c to Vector2D (x, y) else null
@@ -34,27 +42,31 @@ object Day21 : DayOf2024(21) {
34
42
return lines.sumOf { line ->
35
43
val code = pattern.find(line)?.value?.toIntOrNull() ? : 0
36
44
45
+ val cache = mutableMapOf<Triple <Vector2D , Vector2D , Int >, Long > ()
46
+
37
47
val length = " A$line "
38
- .zipWithNext { a, b -> bestPath(digits, arms, digitsMap[a]!! , digitsMap[b]!! , 0 ) }
48
+ .zipWithNext { a, b ->
49
+ bestPath(digits, arms, digitsMap[a]!! , digitsMap[b]!! , 0 , robots + 1 , cache)
50
+ }
39
51
.sum()
40
52
41
53
code * length
42
54
}
43
55
}
44
56
45
- private val bestCache = mutableMapOf<Triple <Vector2D , Vector2D , Int >, Int > ()
46
-
47
57
private fun bestPath (
48
58
matrix : List <List <Char >>,
49
59
handler : List <List <Char >>,
50
60
from : Vector2D ,
51
61
to : Vector2D ,
52
62
level : Int ,
53
- ): Int {
63
+ maxLevel : Int ,
64
+ cache : MutableMap <Triple <Vector2D , Vector2D , Int >, Long >,
65
+ ): Long {
54
66
val config = Triple (from, to, level)
55
67
return when {
56
- level == 3 -> 1
57
- config in bestCache -> bestCache [config]!!
68
+ level == maxLevel -> 1
69
+ config in cache -> cache [config]!!
58
70
from == to -> 1
59
71
else -> {
60
72
val delta = to - from
@@ -91,11 +103,11 @@ object Day21 : DayOf2024(21) {
91
103
chars.zipWithNext().sumOf { (fromChar, toChar) ->
92
104
val fromPoint = handler.find(fromChar)!!
93
105
val toPoint = handler.find(toChar)!!
94
- bestPath(handler, handler, fromPoint, toPoint, level + 1 )
106
+ bestPath(handler, handler, fromPoint, toPoint, level + 1 , maxLevel, cache )
95
107
}
96
108
}
97
109
98
- bestCache [config] = best
110
+ cache [config] = best
99
111
best
100
112
}
101
113
}
0 commit comments