forked from tpatel/advent-of-code-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.js
115 lines (106 loc) · 2.38 KB
/
day10.js
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const fs = require("fs");
const lines = fs
.readFileSync("day10.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.split("\n") // Split on newline
.filter(Boolean); // Remove empty lines
function median(array) {
//taken from day 7
const internalArray = [...array];
internalArray.sort((a, b) => a - b);
if (internalArray.length % 2 === 0) {
return (
(internalArray[internalArray.length / 2 - 1] +
internalArray[internalArray.length / 2]) /
2
);
} else {
return internalArray[Math.floor(internalArray.length / 2)];
}
}
function part1() {
const closingChar = {
"(": ")",
"{": "}",
"[": "]",
"<": ">",
};
const point = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
};
const found = {
")": 0,
"]": 0,
"}": 0,
">": 0,
};
for (const line of lines) {
const stack = [];
for (let i = 0; i < line.length; i++) {
const element = line[i];
if (/[({\[<]/.test(element)) {
stack.push(closingChar[element]);
} else {
const expected = stack.pop();
if (expected !== element) {
//corrupted line
found[element]++;
break;
}
}
}
}
const score = Object.keys(found)
.map((key) => point[key] * found[key])
.reduce((a, b) => a + b, 0);
console.log(score);
}
part1();
function part2() {
const closingChar = {
"(": ")",
"{": "}",
"[": "]",
"<": ">",
};
const points = {
")": 1,
"]": 2,
"}": 3,
">": 4,
};
const scores = [];
for (const line of lines) {
const stack = [];
let corrupted = false;
for (let i = 0; i < line.length; i++) {
const element = line[i];
if (/[({\[<]/.test(element)) {
stack.push(closingChar[element]);
} else {
const expected = stack.pop();
if (expected !== element) {
//corrupted line
corrupted = true;
break;
}
}
}
if (!corrupted && stack.length > 0) {
// incomplete line
const closingChars = stack.reverse().join("");
let score = 0;
for (let i = 0; i < closingChars.length; i++) {
const element = closingChars[i];
score *= 5;
score += points[element];
}
scores.push(score);
}
}
console.log(median(scores));
}
part2();