-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPart1.java
More file actions
107 lines (88 loc) · 3.09 KB
/
Copy pathPart1.java
File metadata and controls
107 lines (88 loc) · 3.09 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package y2016.d07;
import common.Files;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Part1 {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> lines = Files.readByLines("src/main/java/y2016/d07/in.txt");
int countTLS = 0;
int countSSL = 0;
for (String line: lines) {
System.out.println(line + " --- " + hasTLS(line));
if (hasTLS(line)) {
++countTLS;
}
if (hasSSL(line)) {
++countSSL;
}
}
System.out.println(countTLS);
System.out.println(countSSL);
}
private static boolean hasTLS(String line) {
String[] split = line.split("[\\[\\]]");
boolean outsideFound = false;
for (int i = 0; i < split.length; i++) { // always an odd number of strings, the even ones are within brackets.
if (0 == i % 2 && hasAbba(split[i])) {
outsideFound = true;
} else if (1 == i % 2 && hasAbba(split[i])) { // inside one found -- immediate fail!
return false;
}
}
return outsideFound;
}
private static boolean hasSSL(String line) {
String[] split = line.split("[\\[\\]]");
ArrayList<String> outer = new ArrayList<>();
ArrayList<String> inner = new ArrayList<>();
for (int i = 0; i < split.length; i++) { // always an odd number of strings, the even ones are within brackets.
if (0 == i % 2) {
outer.add(split[i]);
} else {
inner.add(split[i]);
}
}
ArrayList<String> abas = getAbas(outer);
for (String aba: abas) {
if (hasBab(aba, inner)) {
return true;
}
}
return false;
}
private static boolean hasBab(String aba, ArrayList<String> inner) {
String bab = String.valueOf(aba.charAt(1)) + aba.charAt(0) + aba.charAt(1);
System.out.println(bab);
for (String in: inner) {
if (in.contains(bab)) {
return true;
}
}
return false;
}
private static ArrayList<String> getAbas(ArrayList<String> outer) {
ArrayList<String> abas = new ArrayList<>();
for (String elem: outer) {
// can't use "match all" as we need to cover overlapping patterns too!
for (int i = 0; i < elem.length()-2; i++) {
String substr = elem.substring(i, i+3);
if (substr.matches("(\\w)(\\w)(\\1)")) {
abas.add(substr);
}
}
}
return abas;
}
private static boolean hasAbba(String in) {
Pattern pattern = Pattern.compile("(\\w)(\\w)(\\2)(\\1)");
Matcher matcher = pattern.matcher(in);
while (matcher.find()) {
if (!matcher.group(1).equals(matcher.group(2))) {
return true;
}
}
return false;
}
}