-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday10question2.ts
More file actions
81 lines (62 loc) · 1.68 KB
/
day10question2.ts
File metadata and controls
81 lines (62 loc) · 1.68 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
import { readFileSync } from "fs";
const openingCharacters = ["(", "[", "{", "<"];
const characterMap = new Map<string, string>([
[")", "("],
["]", "["],
["}", "{"],
[">", "<"],
]);
const scoreMap = new Map<string, number>([
["(", 1],
["[", 2],
["{", 3],
["<", 4],
]);
class ChunkLine {
private _lineCharacters: string[];
public get lineCharacters(): string[] {
return this._lineCharacters;
}
private set lineCharacters(value: string[]) {
this._lineCharacters = value;
}
constructor(line: string) {
this.lineCharacters = line.split("");
}
public score() {
let openingStack: string[] = [];
for (let character of this.lineCharacters) {
if (openingCharacters.some((c) => c === character)) {
openingStack.push(character);
} else {
let matchingCharacter = characterMap.get(character);
if (matchingCharacter !== openingStack.pop()) {
return 0;
}
}
}
return openingStack
.reverse()
.reduce(
(rollingReduction, currentCharacter) =>
rollingReduction * 5 + scoreMap.get(currentCharacter),
0
);
}
}
let inputs: string[];
const rawData = readFileSync("./day10inputs.txt", "utf8");
inputs = rawData.split("\r\n");
let chunkLines = inputs.map((i) => new ChunkLine(i));
let completionScores: number[] = [];
for (let chunkLine of chunkLines) {
let completionScore = chunkLine.score();
if (completionScore !== 0) {
completionScores.push(completionScore);
}
}
console.log(
completionScores.sort((a, b) => a - b)[
Math.floor(completionScores.length / 2)
]
);