-
Notifications
You must be signed in to change notification settings - Fork 0
/
d8.java
82 lines (77 loc) · 2.95 KB
/
d8.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Pattern;
import static java.lang.System.out;
public class d8 {
public static void main(String[] args) {
var reader = new BufferedReader(new InputStreamReader(System.in));
var numbers = new int[]{0};
var segments = Pattern.compile("[a-z]+");
var decoded = new ArrayList<Integer>();
var mappings = new Permutations("abcdefg");
var templates = new String[] {"abcefg", "cf", "acdeg", "acdfg", "bcdf", "abdfg", "abdefg", "acf", "abcdefg", "abcdfg"};
reader.lines().forEach(line -> {
var parts = line.split("\\|");
var matcher = segments.matcher(parts[1]);
while (matcher.find()) {
var l = matcher.group().length();
if (l == 2 || l == 3 || l == 4 || l == 7) {
numbers[0]++;
}
}
var numSegments = new ArrayList<String>();
matcher = segments.matcher(parts[0]);
while (matcher.find()) numSegments.add(matcher.group());
for (var mapping : mappings) {
var valid = new HashSet<Integer>();
for (var numSeg : numSegments) {
for (int n = 0; n < templates.length; n++) {
if (templates[n].equals(map(mapping, numSeg))) {
valid.add(n);
}
}
}
if (valid.size() == 10) {
matcher = segments.matcher(parts[1]);
var nn = 0;
while (matcher.find()) {
for (int n = 0; n < templates.length; n++) {
if (templates[n].equals(map(mapping, matcher.group()))) {
nn = nn * 10 + n;
break;
}
}
}
decoded.add(nn);
break;
}
}
});
out.println(numbers[0]);
out.println(decoded.stream().mapToInt(Integer::intValue).sum());
}
static String map(String mapping, String s) {
char[] result = s.toCharArray();
for (int i = 0; i < result.length; i++) {
result[i] = mapping.charAt(result[i] - 'a');
}
Arrays.sort(result);
return new String(result);
}
static class Permutations extends ArrayList<String> {
Permutations(String s) {
generate("", s);
}
private void generate(String prefix, String str) {
int n = str.length();
if (n == 0) {
this.add(prefix);
} else {
for (int i = 0; i < n; i++) {
generate(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
}
}
}