Skip to content

Commit fb2d755

Browse files
committed
solve 21st day 2nd task
1 parent 9ebaba6 commit fb2d755

File tree

1 file changed

+20
-8
lines changed
  • year2024/src/main/kotlin/net/olegg/aoc/year2024/day21

1 file changed

+20
-8
lines changed

year2024/src/main/kotlin/net/olegg/aoc/year2024/day21/Day21.kt

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ object Day21 : DayOf2024(21) {
2525
""".trimIndent().lines().map { it.toList() }
2626

2727
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 {
2836
val digitsMap = digits.flatMapIndexed { y, row ->
2937
row.mapIndexedNotNull { x, c ->
3038
if (c != ' ') c to Vector2D(x, y) else null
@@ -34,27 +42,31 @@ object Day21 : DayOf2024(21) {
3442
return lines.sumOf { line ->
3543
val code = pattern.find(line)?.value?.toIntOrNull() ?: 0
3644

45+
val cache = mutableMapOf<Triple<Vector2D, Vector2D, Int>, Long>()
46+
3747
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+
}
3951
.sum()
4052

4153
code * length
4254
}
4355
}
4456

45-
private val bestCache = mutableMapOf<Triple<Vector2D, Vector2D, Int>, Int>()
46-
4757
private fun bestPath(
4858
matrix: List<List<Char>>,
4959
handler: List<List<Char>>,
5060
from: Vector2D,
5161
to: Vector2D,
5262
level: Int,
53-
): Int {
63+
maxLevel: Int,
64+
cache: MutableMap<Triple<Vector2D, Vector2D, Int>, Long>,
65+
): Long {
5466
val config = Triple(from, to, level)
5567
return when {
56-
level == 3 -> 1
57-
config in bestCache -> bestCache[config]!!
68+
level == maxLevel -> 1
69+
config in cache -> cache[config]!!
5870
from == to -> 1
5971
else -> {
6072
val delta = to - from
@@ -91,11 +103,11 @@ object Day21 : DayOf2024(21) {
91103
chars.zipWithNext().sumOf { (fromChar, toChar) ->
92104
val fromPoint = handler.find(fromChar)!!
93105
val toPoint = handler.find(toChar)!!
94-
bestPath(handler, handler, fromPoint, toPoint, level + 1)
106+
bestPath(handler, handler, fromPoint, toPoint, level + 1, maxLevel, cache)
95107
}
96108
}
97109

98-
bestCache[config] = best
110+
cache[config] = best
99111
best
100112
}
101113
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy