-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay23.java
79 lines (68 loc) · 2.27 KB
/
Day23.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
import com.horstmann.adventofcode.*;
void parse(Path path) throws IOException {
edges = Files.lines(path).map(l -> Set.of(l.split("-"))).map(Clique::new).collect(Collectors.toSet());
vertices = new TreeSet<>();
for (var c : edges) { vertices.addAll(c.vertices); }
}
static boolean adjacent(String v, String w) { return edges.contains(new Clique(Set.of(v, w))); }
record Clique(Set<String> vertices) {
boolean hasChief() {
return vertices.stream().anyMatch(s -> s.startsWith("t"));
}
boolean allAdjacentTo(String v) {
return !vertices.contains(v) && vertices.stream().allMatch(w -> adjacent(v, w));
}
public String toString() { return new TreeSet<>(vertices).toString().replaceAll(" ", ""); }
}
static Set<Clique> edges;
Set<String> vertices;
Set<Clique> triangles;
Set<String> triangleVertices;
Object part1() {
triangles = new HashSet<>();
triangleVertices = new TreeSet<>();
for (var e : edges) {
for (var w : vertices) {
if (e.allAdjacentTo(w)) {
var c = new Clique(Sets.union(e.vertices, Set.of(w)));
if (c.hasChief()) {
triangles.add(c);
triangleVertices.addAll(c.vertices);
}
}
}
}
return triangles.size();
}
Object part2() {
var cliques = triangles;
var cliqueVertices = triangleVertices;
for (;;) {
var biggerCliques = new HashSet<Clique>();
var biggerCliqueVertices = new TreeSet<String>();
for (var e : cliques) {
for (var w : cliqueVertices) {
if (e.allAdjacentTo(w)) {
var c = new Clique(Sets.union(e.vertices, Set.of(w)));
biggerCliques.add(c);
biggerCliqueVertices.addAll(c.vertices);
}
}
}
if (biggerCliques.isEmpty()) return cliques;
else {
cliques = biggerCliques;
cliqueVertices = biggerCliqueVertices;
}
}
}
void main() throws IOException {
Util.time(() -> {
parse(Util.inputPath("a"));
IO.println(part1());
IO.println(part2());
parse(Util.inputPath("z"));
IO.println(part1());
IO.println(part2());
});
}