Skip to content

Commit da0c8cc

Browse files
committed
Add optimized via pair solution to 2025 day 11
1 parent afeb374 commit da0c8cc

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,45 @@ object Day11 {
5959
override object Part2 extends ViaMapPartSolution with Part2Devices
6060
}
6161

62+
/**
63+
* Optimized version of [[ViaMapSolution]], which only keeps the largest key pair from the mapping.
64+
* Others are useless for passing all the vias.
65+
*/
66+
object ViaPairSolution extends Solution {
67+
trait ViaPairPartSolution extends PartSolution {
68+
override def countPaths(devices: Devices): Long = {
69+
val memo = mutable.Map.empty[Device, (Set[Device], Long)]
70+
71+
def helper(device: Device): (Set[Device], Long) = {
72+
memo.getOrElseUpdate(device, {
73+
val deviceVia = via.intersect(Set(device))
74+
if (device == to)
75+
deviceVia -> 1
76+
else {
77+
val (a, b) = devices(device).map(helper).foldLeft(Set.empty[Device] -> 0L)({ case (a@(accVia, acc), n@(newVia, newCount)) =>
78+
if (accVia == newVia)
79+
accVia -> (acc + newCount)
80+
else if (accVia subsetOf newVia)
81+
n
82+
else if (newVia subsetOf accVia)
83+
a
84+
else
85+
throw new IllegalStateException("")
86+
})
87+
a.union(deviceVia) -> b
88+
}
89+
})
90+
}
91+
92+
helper(from)._2
93+
}
94+
}
95+
96+
override object Part1 extends ViaPairPartSolution with Part1Devices
97+
98+
override object Part2 extends ViaPairPartSolution with Part2Devices
99+
}
100+
62101
/**
63102
* Solution, which tries all permutations of vias and counts each one by multiplying adjacent steps.
64103
*/

src/test/scala/eu/sim642/adventofcode2025/Day11Test.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import org.scalatest.funsuite.AnyFunSuite
77

88
class Day11Test extends Suites(
99
new ViaMapSolutionTest,
10+
new ViaPairSolutionTest,
1011
new PermutationSolutionTest,
1112
)
1213

@@ -59,5 +60,7 @@ object Day11Test {
5960

6061
class ViaMapSolutionTest extends SolutionTest(ViaMapSolution)
6162

63+
class ViaPairSolutionTest extends SolutionTest(ViaPairSolution)
64+
6265
class PermutationSolutionTest extends SolutionTest(PermutationSolution)
6366
}

0 commit comments

Comments
 (0)