8000 Solve 2024 day 18 part 2 · sim642/adventofcode@5a0f957 · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 5a0f957

Browse files
committed
Solve 2024 day 18 part 2
1 parent e476932 commit 5a0f957

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,35 @@ object Day18 {
2626
BFS.search(graphSearch).target.get._2
2727
}
2828

29+
// TODO: deduplicate
30+
def exitSteps2(bytes: Seq[Pos], max: Pos = Pos(70, 70), after: Int = 1024): Boolean = {
31+
val fallenBytes = bytes.take(after).toSet
32+
33+
val graphSearch = new GraphSearch[Pos] with UnitNeighbors[Pos] with TargetNode[Pos] {
34+
override val startNode: Pos = Pos.zero
35+
36+
override def unitNeighbors(pos: Pos): IterableOnce[Pos] = {
37+
for {
38+
offset <- Pos.axisOffsets
39+
newPos = pos + offset
40+
if Pos.zero <= newPos && newPos <= max
41+
if !fallenBytes(newPos)
42+
} yield newPos
43+
}
44+
45+
override val targetNode: Pos = max
46+
}
47+
48+
BFS.search(graphSearch).target.isDefined
49+
}
50+
51+
def findBlockingByte(bytes: Seq[Pos], max: Pos = Pos(70, 70)): String = {
52+
// TODO: optimize (~5.7s)
53+
val after = (0 to bytes.size).find(after => !exitSteps2(bytes, max, after)).get
54+
val afterPos = bytes(after - 1)
55+
s"${afterPos.x},${afterPos.y}"
56+
}
57+
2958
def parseByte(s: String): Pos = s match {
3059
case s"$x,$y" => Pos(x.toInt, y.toInt)
3160
}
@@ -36,5 +65,6 @@ object Day18 {
3665

3766
def main(args: Array[String]): Unit = {
3867
println(exitSteps(parseBytes(input)))
68+
println(findBlockingByte(parseBytes(input)))
3969
}
4070
}

src/test/scala/eu/sim642/adventofcode2024/Day18Test.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,12 @@ class Day18Test extends AnyFunSuite {
4040
test("Part 1 input answer") {
4141
assert(exitSteps(parseBytes(input)) == 304)
4242
}
43+
44+
test("Part 2 examples") {
45+
assert(findBlockingByte(parseBytes(exampleInput), Pos(6, 6)) == "6,1")
46+
}
47+
48+
ignore("Part 2 input answer") { // TODO: optimize (~5.7s)
49+
assert(findBlockingByte(parseBytes(input)) == "50,28")
50+
}
4351
}

0 commit comments

Comments
 (0)
0