-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay7.ts
92 lines (77 loc) · 2.4 KB
/
Day7.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
87
88
89
90
91
92
import * as fs from 'fs';
import * as _ from 'lodash';
class Solution {
private graph = {};
private directions: Direction[];
constructor(private lines: string[]) {
this.directions = this.lines.map(x => this.parse(x));
}
private parse(line: string): Direction {
let re = /Step (?<from>[a-zA-Z]+) must be finished before step (?<to>[a-zA-Z]+) can begin./
let result = <any>line.match(re);
return result.groups;
}
answer1() {
for (const direction of this.directions) {
let nodeFrom = this.graph[direction.from];
if (nodeFrom === undefined) {
nodeFrom = <Node>{
value: direction.from,
children: [],
parents: []
}
this.graph[direction.from] = nodeFrom;
}
let nodeTo = this.graph[direction.to];
if (nodeTo === undefined) {
nodeTo = <Node>{
value: direction.to,
children: [],
parents: []
}
this.graph[direction.to] = nodeTo;
}
nodeTo.parents.push(nodeFrom);
nodeFrom.children.push(nodeTo);
}
const root = this.getRoot();
root.level = 0;
let result = '';
let stack: Node[] = [];
stack.push(root);
while (stack.length != 0) {
const el = _.sortBy(stack.filter(a => a.parents.every(a => a.visited)), ['value'])[0];
stack.splice(stack.indexOf(el), 1);
for (const child of el.children) {
child.level = el.level + 1;
if(!stack.filter(x => x.value === child.value)[0]) {
stack.push(child);
}
}
el.visited = true;
result += el.value;
}
return result;
}
getRoot(): Node {
for (const nodeIndex in this.graph) {
if (!this.graph[nodeIndex].parent) return this.graph[nodeIndex];
}
return null;
}
}
class Direction {
from: string;
to: string;
}
class Node {
parents: Node[];
value: string;
children: Node[];
level: number;
visited: boolean;
}
const lines = fs.readFileSync('./Day7.txt').toString().split("\n");
const sln = new Solution(lines);
const result = sln.answer1();
console.log(result);