@@ -6,8 +6,7 @@ object Day11 {
66
77 type Device = String
88
9- def countPaths (devices : Map [Device , Seq [Device ]], from : Device = " you" , to : Device = " out" ): Int = { // TODO: Long?
10-
9+ def countPaths (devices : Map [Device , Seq [Device ]], from : Device = " you" , to : Device = " out" ): Int = {
1110 val memo = mutable.Map .empty[Device , Int ]
1211
1312 def helper (device : Device ): Int = {
@@ -22,6 +21,23 @@ object Day11 {
2221 helper(from)
2322 }
2423
24+ def countPaths2 (devices : Map [Device , Seq [Device ]], from : Device = " svr" , to : Device = " out" ): Long = {
25+ val vias = Set (" dac" , " fft" )
26+
27+ val memo = mutable.Map .empty[Device , Map [Set [Device ], Long ]]
28+
29+ def helper (device : Device ): Map [Set [Device ], Long ] = {
30+ memo.getOrElseUpdate(device, {
31+ if (device == to)
32+ Map (Set .empty -> 1 )
33+ else
34+ devices(device).flatMap(helper).groupMapReduce(_._1)(_._2)(_ + _).map((k, v) => (k.union(vias.intersect(Set (device)))) -> v)
35+ })
36+ }
37+
38+ helper(from)(vias)
39+ }
40+
2541 def parseDevice (s : String ): (Device , Seq [Device ]) = s match {
2642 case s " $key: $values" => key -> values.split(" " ).toSeq
2743 }
@@ -32,5 +48,6 @@ object Day11 {
3248
3349 def main (args : Array [String ]): Unit = {
3450 println(countPaths(parseDevices(input)))
51+ println(countPaths2(parseDevices(input)))
3552 }
3653}
0 commit comments