-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
86 lines (70 loc) · 2.06 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
import {
INPUT_PATH,
runner,
SAMPLE_PATH,
splitLines,
} from '../../../lib/utils';
const path = `${__dirname}/${INPUT_PATH}`;
type Graph = Map<string, Set<string>>;
const getGraph = (data: string[][]) => {
const graph: Graph = new Map();
for (const [left, right] of data) {
if (!graph.has(left)) graph.set(left, new Set());
if (!graph.has(right)) graph.set(right, new Set());
graph.get(left)!.add(right);
graph.get(right)!.add(left);
}
return graph;
};
const solution = (input: string) => {
const data = splitLines(input).map((r) => r.split('-'));
const connections: Set<string> = new Set();
const graph = getGraph(data);
for (const [node1, node2level] of graph) {
if (!node1.startsWith('t')) continue;
for (const node2 of node2level) {
for (const node3 of graph.get(node2) || new Set()) {
for (const node4 of graph.get(node3) || new Set()) {
if (node4 === node1) {
connections.add([node1, node2, node3].sort().join(','));
}
}
}
}
}
return connections.size;
};
const hasAllConnetions = (root: string, rest: Set<string>, graph: Graph) => {
const children = graph.get(root) || new Set();
return Array.from(rest).every(
(vertex) => vertex === root || children.has(vertex),
);
};
const solution2 = (input: string) => {
const data = splitLines(input).map((r) => r.split('-'));
let connections: string[] = [];
const graph = getGraph(data);
const vertexHeads = Array.from(graph.keys());
for (const head of vertexHeads) {
const curr: string[] = [head];
const headChildren = graph.get(head) || new Set();
for (const child of headChildren) {
const children = graph.get(child) || new Set();
if (curr.every((vertex) => children.has(vertex))) {
curr.push(child);
}
}
if (connections.length < curr.length) connections = curr;
}
return connections.sort().join();
};
runner({
path,
name: 'Part1',
solution: (input) => solution(input),
});
runner({
path,
name: 'Part2',
solution: (input) => solution2(input),
});