-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10.ts
97 lines (90 loc) · 2.54 KB
/
10.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
93
94
95
96
97
import * as fs from 'fs';
import { compact, sum } from 'lodash';
import { log } from './utils';
const input: string[] = compact(fs.readFileSync('./10.txt', { encoding: 'utf-8' }).split('\n'));
function getOpeningChar(char: string): string {
return new Map([
[')', '('],
[']', '['],
['}', '{'],
['>', '<'],
]).get(char)!;
}
function isClosingChar(char: string): boolean {
return [')', ']', '}', '>'].includes(char);
}
function part1(): void {
const result = sum(
compact(
input.map(line => {
const stack: string[] = [];
for (let char of line) {
if (isClosingChar(char)) {
const lastChar = stack.pop();
if (getOpeningChar(char) !== lastChar) {
return char;
}
} else {
stack.push(char);
}
}
return undefined;
}),
).map(
char =>
new Map([
[')', 3],
[']', 57],
['}', 1197],
['>', 25137],
]).get(char)!,
),
);
log(result);
}
function getClosingChar(char: string): string {
return new Map([
['(', ')'],
['[', ']'],
['{', '}'],
['<', '>'],
]).get(char)!;
}
function part2(): void {
const sortedScores = compact(
input.map(line => {
const stack: string[] = [];
for (let char of line) {
if (isClosingChar(char)) {
const lastChar = stack.pop();
if (getOpeningChar(char) !== lastChar) {
return false;
}
} else {
stack.push(char);
}
}
return stack;
}),
)
.map(stack => stack.reverse().map(getClosingChar))
.map(missingChars => {
let total = 0;
for (let char of missingChars) {
total =
total * 5 +
new Map([
[')', 1],
[']', 2],
['}', 3],
['>', 4],
]).get(char)!;
}
return total;
})
.sort((a, b) => a - b);
const result = sortedScores[Math.ceil(sortedScores.length / 2) - 1];
log(result);
}
part1();
part2();