Published
Edited
Dec 13, 2021
Insert cell
Insert cell
Insert cell
Insert cell
lines = input.split("\n")
Insert cell
function isLineValid(line) {
const pairs = {
")": "(",
"]": "[",
"}": "{",
">": "<"
};

let stack = [];
for (const char of [...line]) {
if (Object.values(pairs).includes(char)) {
// opening symbol, push onto stack
stack.push(char);
} else if (Object.keys(pairs).includes(char)) {
// closing symbol, pop off stack
const popped = stack.pop();
if (pairs[char] !== popped) {
return [false, char];
}
} else {
throw new Error("Unknown symbol");
}
}

return [true, stack];
}
Insert cell
{
let score = 0;
const points = {
")": 3,
"]": 57,
"}": 1197,
">": 25137
};
for (const line of lines) {
const [valid, errChar] = isLineValid(line);
if (!valid) {
score += points[errChar];
}
}
return score;
}
Insert cell
Insert cell
{
const incompleteLines = lines
.map((l) => isLineValid(l))
.filter((result) => result[0]);
let score = 0;
const points = {
"(": 1,
"[": 2,
"{": 3,
"<": 4
};
// score the remaining
const scores = incompleteLines.map(([, stack]) =>
stack.reverse().reduce((acc, val) => acc * 5 + points[val], 0)
);
return scores.sort((a, b) => a - b)[Math.floor(scores.length / 2)];
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more