Skip to content

Commit 635e1c4

Browse files
committed
Deduplicate graph search in 2024 day 18
1 parent d59d7e6 commit 635e1c4

File tree

1 file changed

+11
-25
lines changed

1 file changed

+11
-25
lines changed

src/main/scala/eu/sim642/adventofcode2024/Day18.scala

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ import eu.sim642.adventofcodelib.pos.Pos
66

77
object Day18 {
88

9-
def exitSteps(bytes: Seq[Pos], max: Pos = Pos(70, 70), after: Int = 1024): Int = {
9+
def bytesGraphSearch(bytes: Seq[Pos], max: Pos = Pos(70, 70), after: Int = 1024): GraphSearch[Pos] & UnitNeighbors[Pos] & TargetNode[Pos] = {
1010
val fallenBytes = bytes.take(after).toSet
1111

12-
val graphSearch = new GraphSearch[Pos] with UnitNeighbors[Pos] with TargetNode[Pos] {
12+
new GraphSearch[Pos] with UnitNeighbors[Pos] with TargetNode[Pos] {
1313
override val startNode: Pos = Pos.zero
1414

1515
override def unitNeighbors(pos: Pos): IterableOnce[Pos] = {
@@ -23,37 +23,23 @@ object Day18 {
2323

2424
override val targetNode: Pos = max
2525
}
26+
}
2627

28+
def exitSteps(bytes: Seq[Pos], max: Pos = Pos(70, 70), after: Int = 1024): Int = {
29+
val graphSearch = bytesGraphSearch(bytes, max, after)
2730
BFS.search(graphSearch).target.get._2
2831
}
2932

30-
// TODO: deduplicate
31-
def exitSteps2(bytes: Seq[Pos], max: Pos = Pos(70, 70), after: Int = 1024): Boolean = {
32-
val fallenBytes = bytes.take(after).toSet
33-
34-
val graphSearch = new GraphSearch[Pos] with UnitNeighbors[Pos] with TargetNode[Pos] {
35-
override val startNode: Pos = Pos.zero
36-
37-
override def unitNeighbors(pos: Pos): IterableOnce[Pos] = {
38-
for {
39-
offset <- Pos.axisOffsets
40-
newPos = pos + offset
41-
if Pos.zero <= newPos && newPos <= max
42-
if !fallenBytes(newPos)
43-
} yield newPos
44-
}
45-
46-
override val targetNode: Pos = max
47-
}
48-
33+
def exitReachable(bytes: Seq[Pos], max: Pos, after: Int): Boolean = {
34+
val graphSearch = bytesGraphSearch(bytes, max, after)
4935
BFS.search(graphSearch).target.isDefined
5036
}
5137

5238
def findBlockingByte(bytes: Seq[Pos], max: Pos = Pos(70, 70)): String = {
53-
def f(after: Int): Boolean = !exitSteps2(bytes, max, after)
54-
val after = OrderedSearch.binaryLower(f, 0, bytes.size + 1)(true)
55-
val afterPos = bytes(after - 1)
56-
s"${afterPos.x},${afterPos.y}"
39+
def f(after: Int): Boolean = !exitReachable(bytes, max, after)
40+
val blockingAfter = OrderedSearch.binaryLower(f, 0, bytes.size + 1)(true)
41+
val blockingByte = bytes(blockingAfter - 1)
42+
s"${blockingByte.x},${blockingByte.y}"
5743
}
5844

5945
def parseByte(s: String): Pos = s match {

0 commit comments

Comments
 (0)