1
1
package com .sbaars .adventofcode .year16 .days ;
2
2
3
3
import com .sbaars .adventofcode .year16 .Day2016 ;
4
+ import com .sbaars .adventofcode .common .map .LongCountMap ;
4
5
import java .util .*;
5
6
import java .util .stream .Collectors ;
7
+ import java .util .stream .IntStream ;
6
8
7
9
public class Day6 extends Day2016 {
8
10
public Day6 () {
@@ -15,29 +17,19 @@ public static void main(String[] args) {
15
17
16
18
private String decodeMessage (boolean mostCommon ) {
17
19
List <String > messages = dayStream ().collect (Collectors .toList ());
18
- int messageLength = messages .get (0 ).length ();
19
- StringBuilder result = new StringBuilder ();
20
-
21
- for (int pos = 0 ; pos < messageLength ; pos ++) {
22
- Map <Character , Integer > freq = new HashMap <>();
23
- for (String message : messages ) {
24
- char c = message .charAt (pos );
25
- freq .merge (c , 1 , Integer ::sum );
26
- }
27
-
28
- char selectedChar = freq .entrySet ().stream ()
29
- .sorted ((a , b ) -> {
30
- int comp = mostCommon ? b .getValue ().compareTo (a .getValue ()) : a .getValue ().compareTo (b .getValue ());
31
- return comp != 0 ? comp : a .getKey ().compareTo (b .getKey ());
32
- })
33
- .map (Map .Entry ::getKey )
34
- .findFirst ()
35
- .orElseThrow ();
36
-
37
- result .append (selectedChar );
38
- }
39
-
40
- return result .toString ();
20
+ return IntStream .range (0 , messages .get (0 ).length ())
21
+ .mapToObj (pos -> messages .stream ()
22
+ .map (msg -> msg .charAt (pos ))
23
+ .collect (LongCountMap .toCountMap ()))
24
+ .map (freq -> freq .entrySet ().stream ()
25
+ .sorted ((a , b ) -> mostCommon ?
26
+ b .getValue ().compareTo (a .getValue ()) :
27
+ a .getValue ().compareTo (b .getValue ()))
28
+ .map (Map .Entry ::getKey )
29
+ .findFirst ()
30
+ .orElseThrow ())
31
+ .map (String ::valueOf )
32
+ .collect (Collectors .joining ());
41
33
}
42
34
43
35
@ Override
0 commit comments