Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9233c8a

Browse files
small optimization
1 parent 820f629 commit 9233c8a

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

‎src/main/java/com/codefork/aoc2024/day21/ShipLock.java

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ public static int getNumericPortion(String str) {
2424
}
2525

2626
public static long calculateSumOfComplexities(Stream<String> data, int numRobots) {
27+
record WithLength(PressSequence seq, long length) {
28+
}
29+
2730
// create our layered navigators
2831
var navigators = new ArrayList<KeypadNavigator>();
2932
navigators.add(new DoorKeypadNavigator());
@@ -45,15 +48,25 @@ public static long calculateSumOfComplexities(Stream<String> data, int numRobots
4548
newPressSeqSet.addAll(possiblePresses);
4649
}
4750

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();
4960

5061
// we don't need to carry over every result to the next iteration, only the shortest ones.
5162
// 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();
5367
pressSeqs = truncated;
5468
}
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();
5770
//System.out.println("shortest press found is "+ shortestLength + " long");
5871
var result = shortestLength * getNumericPortion(seq);
5972
return result;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /