Skip to content

Commit c95212f

Browse files
committed
Day 6: Optimize with jump table
1 parent 473e6c1 commit c95212f

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/main/kotlin/y24/Day6.kt

+26-5
Original file line numberDiff line numberDiff line change
@@ -36,32 +36,50 @@ class Day6(val input: Input) : Puzzle {
3636
data class PathResult(
3737
val points: Set<Point>,
3838
val loop: Boolean,
39+
val jumpTable: Map<Pair<Point, Dir>, Point>,
3940
)
4041

41-
private fun findPath(grid: Grid<Boolean>, start: Point): PathResult {
42+
private fun findPath(grid: Grid<Boolean>, start: Point, jumpTable: Map<Pair<Point, Dir>, Point>? = null): PathResult {
4243
var cur = start
4344
val visited = mutableSetOf<Point>()
4445
val visitedWithDir = mutableSetOf<Pair<Point, Dir>>()
4546

47+
val computeNewJumpTable = jumpTable == null
48+
val newJumpTable = mutableMapOf<Pair<Point, Dir>, Point>()
49+
50+
var jumpStart: Point? = null
4651
var dir = 1
4752
while (grid.withinBounds(cur.row, cur.col)) {
4853
visited += cur
4954
if (!visitedWithDir.add(cur to directions[dir])) {
50-
return PathResult(visited, true)
55+
return PathResult(visited, true, newJumpTable)
56+
}
57+
58+
if (computeNewJumpTable) {
59+
if (jumpStart == null) {
60+
jumpStart = cur
61+
}
5162
}
5263

5364
// Assumes no bad input that could lead to an infinite loop
5465
while (true) {
5566
val d = directions[dir]
5667

57-
val next = cur + d.toPoint()
68+
val next = jumpTable?.let { it[cur to d] } ?: (cur + d.toPoint())
5869
if (!grid.withinBounds(next.row, next.col)) {
5970
cur = next
6071
break
6172
}
6273

6374
if (grid[next.row][next.col].value) {
6475
// Obstacle, rotate
76+
if (computeNewJumpTable) {
77+
if (jumpStart != null && jumpStart != cur) {
78+
newJumpTable[jumpStart to d] = cur
79+
}
80+
jumpStart = null
81+
}
82+
6583
dir = (dir + 1) % 4
6684
continue
6785
}
@@ -71,7 +89,7 @@ class Day6(val input: Input) : Puzzle {
7189
}
7290
}
7391

74-
return PathResult(visited, false)
92+
return PathResult(visited, false, newJumpTable)
7593
}
7694

7795
override fun solveLevel1(): Any {
@@ -98,7 +116,10 @@ class Day6(val input: Input) : Puzzle {
98116
}
99117

100118
grid[row][col].value = true
101-
val path = findPath(grid, guard)
119+
val withJumpTable = normalPath.jumpTable.filterKeys { (start, _) ->
120+
start.row != p.row && start.col != p.col
121+
}
122+
val path = findPath(grid, guard, withJumpTable)
102123
if (path.loop) {
103124
numLoops++
104125
}

0 commit comments

Comments
 (0)