Skip to content

Commit 41809ad

Browse files
committed
Optimizing Ram Run algorithm.
1 parent 6cbe2db commit 41809ad

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,6 @@ Here are the solutions I have implemented along with the time it took to run eac
3737
| [Day 15: Warehouse Woes](src/test/kotlin/adventofcode/Day15Test.kt) | 129 |
3838
| [Day 16: Reindeer Maze](src/test/kotlin/adventofcode/Day16Test.kt) | 261 |
3939
| [Day 17: Chronospatial Computer](src/test/kotlin/adventofcode/Day17Test.kt) | 93 |
40-
| [Day 18: RAM Run](src/test/kotlin/adventofcode/Day18Test.kt) | 5,520 |
40+
| [Day 18: RAM Run](src/test/kotlin/adventofcode/Day18Test.kt) | 3,328 |
4141
| [Day 19: Linen Layout](src/test/kotlin/adventofcode/Day19Test.kt) | 60 |
4242
| [Day 20: Race Condition](src/test/kotlin/adventofcode/Day20Test.kt) | 0 |

src/main/kotlin/adventofcode/day18/RamRun.kt

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,18 @@ fun List<Point2D>.generateMap() = TextGrid(List(maxOf { it.y } + 1) { ".".repeat
2828

2929
fun String.findFirstByteThatBlocksExit(): Point2D {
3030
val points = parsePoints()
31-
val map = points.generateMap()
32-
val start = map.coordinates().first()
33-
val end = map.coordinates().last()
34-
val vertices = map.coordinates().filter { map[it] != '#' }.toSet()
35-
val neighbors = { p: Point2D -> p.neighbors().filter { it in map }.filter { map[it] != '#' } }
36-
return points.find { p ->
37-
map[p] = '#'
38-
!Graphs.shortestPaths(start, vertices, neighbors).pathExists(end)
39-
} ?: throw IllegalStateException("No byte blocks exit")
31+
32+
val start = Point2D.origin()
33+
val xRange = 0..points.maxOf { it.x }
34+
val yRange = 0..points.maxOf { it.y }
35+
val end = Point2D(xRange.last, yRange.last)
36+
val fallen = mutableSetOf<Point2D>()
37+
val neighbors =
38+
{ p: Point2D -> p.neighbors().filter { it.x in xRange && it.y in yRange }.filter { it !in fallen} }
39+
return points.first { p ->
40+
fallen.add(p)
41+
Graphs.dfs(start, end, neighbors).isEmpty()
42+
}
4043
}
4144

4245
fun String.findShortestPathToExitAfter(nBytes: Int): Int {

0 commit comments

Comments
 (0)