|
4 | 4 | import java.util.ArrayList;
|
5 | 5 | import java.util.HashSet;
|
6 | 6 | import java.util.List;
|
| 7 | +import java.util.Set; |
7 | 8 | import java.util.stream.Collectors;
|
8 | 9 | import java.util.stream.StreamSupport;
|
9 | 10 |
|
10 | 11 | public class Day06 {
|
11 | 12 |
|
12 | 13 | public static void main(final String[] args) throws IOException {
|
13 |
| - try( var spliterator = new LineSpliterator( Day06.class.getResourceAsStream("/day-6-input.txt" ) ) ) { |
| 14 | + try (var spliterator = new LineSpliterator(Day06.class.getResourceAsStream("/day-6-input.txt"))) { |
14 | 15 | final var rawLines = StreamSupport.stream(spliterator, false)
|
15 | 16 | .collect(Collectors.toUnmodifiableList());
|
16 | 17 | var currentGroup = new ArrayList<String>();
|
17 | 18 | // collect all the text blocks into entries (separated by empty lines)
|
18 | 19 | final var groups = new ArrayList<List<String>>();
|
19 | 20 | for (final var line : rawLines) {
|
20 | 21 | if (line.isBlank()) {
|
21 |
| - if( currentGroup != null && !currentGroup.isEmpty() ) { |
22 |
| - groups.add( currentGroup ); |
| 22 | + if (currentGroup != null && !currentGroup.isEmpty()) { |
| 23 | + groups.add(currentGroup); |
23 | 24 | currentGroup = new ArrayList<>();
|
24 | 25 | }
|
25 | 26 | } else {
|
26 |
| - currentGroup.add( line ); |
| 27 | + currentGroup.add(line); |
27 | 28 | }
|
28 | 29 | }
|
29 |
| - if( currentGroup != null && !currentGroup.isEmpty() ) { |
30 |
| - groups.add( currentGroup ); |
| 30 | + if (currentGroup != null && !currentGroup.isEmpty()) { |
| 31 | + groups.add(currentGroup); |
31 | 32 | }
|
32 | 33 | final int sum = groups.stream().mapToInt(group -> {
|
33 |
| - final var uniqueCharacters = new HashSet<Integer>(); |
34 |
| - for( final var answers : group ) { |
35 |
| - answers.chars().forEach(answer -> { |
36 |
| - uniqueCharacters.add(answer); |
37 |
| - }); |
38 |
| - } |
39 |
| - int total = 0; |
40 |
| - for( final int c : uniqueCharacters ) { |
41 |
| - int numResponses = 0; |
42 |
| - for( final var answers : group ) { |
43 |
| - for( char a : answers.toCharArray() ) { |
44 |
| - if( (int)a == c ) { |
45 |
| - numResponses++; |
46 |
| - break; |
47 |
| - } |
48 |
| - } |
49 |
| - if( numResponses == group.size() ) { |
50 |
| - total++; |
51 |
| - } |
52 |
| - } |
53 |
| - } |
54 |
| - return total; |
| 34 | + final var uniqueCharacters = group.stream() |
| 35 | + .flatMapToInt(String::chars) |
| 36 | + .collect(HashSet<Integer>::new, Set::add, Set::addAll); |
| 37 | + return (int) uniqueCharacters.stream() |
| 38 | + .filter(c -> (int) group.stream() |
| 39 | + .map(String::chars) |
| 40 | + .filter(chars -> chars.anyMatch(answer -> answer == c)) |
| 41 | + .count() == group.size()) |
| 42 | + .count(); |
55 | 43 | }).sum();
|
56 | 44 | System.out.println(sum);
|
57 | 45 | }
|
|
0 commit comments