Skip to content

Commit afeb374

Browse files
committed
Optimize permutation solution in 2025 day 11
1 parent 1f8232d commit afeb374

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/main/scala/eu/sim642/adventofcode2025/Day11.scala

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,15 @@ object Day11 {
8888
@tailrec
8989
def helper(prevDevice: Device, acc: Long, via: List[Device]): Long = via match {
9090
case Nil => acc * countPathsFromTo(prevDevice, to)
91-
case device :: newVia => helper(device, acc * countPathsFromTo(prevDevice, device), newVia) // TODO: optimize: stop when countPathsFromTo is zero
91+
case device :: newVia =>
92+
val newAcc = countPathsFromTo(prevDevice, device)
93+
if (newAcc == 0)
94+
0 // this step is impossible, so no need to continue (multiplying 0)
95+
else
96+
helper(device, acc * newAcc, newVia)
9297
}
9398

94-
via.toList.permutations.map(helper(from, 1L, _)).sum // TODO: optimize: only one can be non-zero, stop on first
99+
via.toList.permutations.map(helper(from, 1L, _)).find(_ != 0).get // this could be a sum, but only one vias permutation can be non-zero, so stop after finding that one, no need to continue (adding 0s)
95100
}
96101
}
97102

0 commit comments

Comments
 (0)