Skip to content

Commit 36207f6

Browse files
committed
2024 - Day 20 - rewrote - there is only one path!
1 parent de38817 commit 36207f6

File tree

1 file changed

+17
-39
lines changed
  • src/main/kotlin/no/rodland/advent_2024

1 file changed

+17
-39
lines changed

src/main/kotlin/no/rodland/advent_2024/Day20.kt

Lines changed: 17 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -23,49 +23,27 @@ class Day20(val input: List<String>) : Day<Int, Int, Pair<Array<CharArray>, Pair
2323
}
2424

2525
private fun solve(maxDistance: Int, lim: Int): Int {
26-
val shortestPath = bfs(start, end)
27-
val size = shortestPath.size
28-
val fromStart = shortestPath.mapIndexed { idx, pos -> pos to idx }.toMap()
29-
val toEnd = shortestPath.mapIndexed { idx, pos -> pos to size - idx }.toMap()
30-
return shortestPath
31-
.asSequence()
32-
.flatMapIndexed { idx, from ->
33-
shortestPath
34-
.subList(idx + 1, size)
35-
.mapNotNull { to -> from.manhattanDistance(to).let { if (it in 2..maxDistance) it to to else null } }
36-
.map { to -> size - (fromStart[from]!! + to.first + toEnd[to.second]!!) }
37-
.filter { it > 0 }
26+
val shortestPath = getPath().toTypedArray()
27+
return shortestPath.indices
28+
.sumOf { from ->
29+
((from + lim)..<shortestPath.size).count { end ->
30+
val manhattan = shortestPath[from].manhattanDistance(shortestPath[end])
31+
manhattan <= maxDistance && manhattan <= end - from - lim
32+
}
3833
}
39-
.groupBy { it }
40-
.filterKeys { it >= lim }
41-
.map { it.value.size }
42-
.sum()
4334
}
4435

45-
46-
private tailrec fun bfs(
47-
start: Pos,
48-
end: Pos,
49-
queue: ArrayDeque<List<Pos>> = ArrayDeque(listOf(listOf(start))),
50-
visited: MutableSet<Pos> = mutableSetOf(start)
51-
): List<Pos> {
52-
if (queue.isEmpty()) return emptyList()
53-
// Dequeue the current path
54-
val path = queue.removeFirst()
55-
val current = path.last()
56-
57-
// Check if we reached the end position
58-
if (current == end) return path
59-
current.neighbourCellsUDLR()
60-
.filter { it !in visited }
61-
.filter { it in racetrack }
62-
.filter { racetrack[it] != '#' }
63-
.forEach { neighbor ->
64-
visited.add(neighbor)
65-
queue.add(path + neighbor) // Enqueue the new path
36+
private fun getPath(): List<Pos> {
37+
return mutableListOf(start).apply {
38+
while (last() != end) {
39+
add(
40+
last()
41+
.neighbourCellsUDLR()
42+
.filter { racetrack[it] != '#' }
43+
.first { it != getOrNull(lastIndex - 1) }
44+
)
6645
}
67-
// Recursive call with the updated queue and visited set
68-
return bfs(start, end, queue, visited)
46+
}
6947
}
7048

7149
override fun List<String>.parse(): Pair<Array<CharArray>, Pair<Pos, Pos>> {

0 commit comments

Comments
 (0)