11package com .sbaars .adventofcode .year16 .days ;
22
33import com .sbaars .adventofcode .year16 .Day2016 ;
4+ import com .sbaars .adventofcode .common .map .LongCountMap ;
45import java .util .*;
56import java .util .stream .Collectors ;
7+ import java .util .stream .IntStream ;
68
79public class Day6 extends Day2016 {
810 public Day6 () {
@@ -15,29 +17,19 @@ public static void main(String[] args) {
1517
1618 private String decodeMessage (boolean mostCommon ) {
1719 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 ());
4133 }
4234
4335 @ Override
0 commit comments