-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.ts
73 lines (66 loc) · 2.46 KB
/
solver.ts
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
import { PuzzleSolver } from "../types/puzzle-solver.ts";
export default class Solver24D23 implements PuzzleSolver {
private adjacencyList = new Map<string, string[]>();
parseInput(input: string[]) {
for (const line of input.filter((line) => !!line)) {
const [a, b] = line.split("-");
if (!this.adjacencyList.has(a)) {
this.adjacencyList.set(a, []);
}
if (!this.adjacencyList.has(b)) {
this.adjacencyList.set(b, []);
}
this.adjacencyList.get(a)!.push(b);
this.adjacencyList.get(b)!.push(a);
}
}
solvePart1() {
const groupsOf3 = new Set<string>();
for (const [computer, neighbors] of this.adjacencyList.entries()) {
if (!computer.startsWith("t")) {
continue;
}
for (const neighbor of neighbors) {
for (const neighbor2 of this.adjacencyList.get(neighbor)!) {
if (neighbor2 === computer || neighbor2 === neighbor) {
continue;
}
for (const neighbor3 of this.adjacencyList.get(
neighbor2
)!) {
if (neighbor3 !== computer) {
continue;
}
const group = [computer, neighbor, neighbor2]
.sort()
.join(",");
groupsOf3.add(group);
}
}
}
}
return groupsOf3.size;
}
solvePart2() {
let biggestGroup = new Array<string>();
for (const computer of this.adjacencyList.keys()) {
const group = this.getInterconnected(computer);
if (group.length > biggestGroup.length) biggestGroup = group;
}
return biggestGroup.sort().join(",");
}
private getInterconnected(computer: string) {
const neighbors = this.adjacencyList.get(computer)!;
let group = new Set([computer, ...neighbors]);
for (const neighbor of neighbors) {
if (!group.has(neighbor)) {
continue;
}
const neighborsOfNeighbor = this.adjacencyList.get(neighbor)!;
group = group.intersection(
new Set([neighbor, ...neighborsOfNeighbor])
);
}
return [...group];
}
}