@@ -24,6 +24,9 @@ public static int getNumericPortion(String str) {
24
24
}
25
25
26
26
public static long calculateSumOfComplexities (Stream <String > data , int numRobots ) {
27
+ record WithLength (PressSequence seq , long length ) {
28
+ }
29
+
27
30
// create our layered navigators
28
31
var navigators = new ArrayList <KeypadNavigator >();
29
32
navigators .add (new DoorKeypadNavigator ());
@@ -45,15 +48,25 @@ public static long calculateSumOfComplexities(Stream<String> data, int numRobots
45
48
newPressSeqSet .addAll (possiblePresses );
46
49
}
47
50
48
- var shortestLength = newPressSeqSet .stream ().map (PressSequence ::length ).mapToLong (i -> i ).min ().orElseThrow ();
51
+ // calculate lengths just once, since it's a slightly expensive operation
52
+ var withLengths = newPressSeqSet .stream ()
53
+ .map (ps -> new WithLength (ps , ps .length ()))
54
+ .toList ();
55
+
56
+ var shortestLength = withLengths .stream ()
57
+ .mapToLong (WithLength ::length )
58
+ .min ()
59
+ .orElseThrow ();
49
60
50
61
// we don't need to carry over every result to the next iteration, only the shortest ones.
51
62
// this shortcut is necessary to get the solution to finish at all
52
- var truncated = newPressSeqSet .stream ().filter (set -> set .length () == shortestLength ).toList ();
63
+ var truncated = withLengths .stream ()
64
+ .filter (item -> item .length () == shortestLength )
65
+ .map (WithLength ::seq )
66
+ .toList ();
53
67
pressSeqs = truncated ;
54
68
}
55
- //System.out.println("found " + pressSeqSet.size() + " possible presses for last navigator");
56
- var shortestLength = pressSeqs .stream ().map (PressSequence ::length ).mapToLong (i -> i ).min ().orElseThrow ();
69
+ var shortestLength = pressSeqs .getFirst ().length ();
57
70
//System.out.println("shortest press found is "+ shortestLength + " long");
58
71
var result = shortestLength * getNumericPortion (seq );
59
72
return result ;
0 commit comments