Day 16: Early exit search loop

This commit is contained in:
Christian
2025-01-24 22:48:14 +01:00
parent 9654c59bfd
commit 2f8dfce29f
2 changed files with 19 additions and 12 deletions

View File

@@ -31,6 +31,7 @@ val solvers = Map[Int, Solver](
)
def runSolver(solver: Solver, input: os.Path): Unit =
for _ <- 0 to 100 do solver.run(input)
val (timings, solution) = solver.run(input)
sys.env.get("AOC_BENCH") match
case Some(_) =>

View File

@@ -3,6 +3,8 @@ package dev.ctsk.aoc.days
import dev.ctsk.aoc.{Direction, *}
import scala.collection.mutable
import scala.util.boundary
import scala.util.boundary.break
object Day16 extends Solver(16):
override def run(input_ : os.ReadablePath): (Timings, Solution) =
@@ -14,7 +16,6 @@ object Day16 extends Solver(16):
val end = grid.findFirst(_ == 'E').get
case class State(distance: Int, pose: Pose)
implicit def ord: Ordering[State] = Ordering.by(-1 * _.distance)
def search(start: Pose): (Map[Pose, Int], Map[Pose, List[Pose]]) =
val distance = mutable.Map(start -> 0)
@@ -32,15 +33,20 @@ object Day16 extends Solver(16):
then far.push(State(vDist, v))
else near.push(State(vDist, v))
boundary:
while near.nonEmpty do
var atEnd = false;
while near.nonEmpty do
val State(uDist, u) = near.pop()
atEnd |= u.pos == end
if uDist == distance(u) then
if !grid(u.step.pos).contains('#') then
relax(u, u.step, uDist + 1, false)
for (v <- Seq(u.turnLeft, u.turnRight)) do
relax(u, v, uDist + 1000, true)
if atEnd then break()
val tmp = near
near = far
far = tmp
@@ -51,7 +57,7 @@ object Day16 extends Solver(16):
search(Pose(start, Direction.Right))
}
val endPose = DIRS.map(Pose(end, _)).minBy(distance(_))
val endPose = DIRS.map(Pose(end, _)).minBy(distance.getOrElse(_, 1_000_000))
val p1 = distance(endPose)