Public
Edited
Dec 10, 2021
1 star
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((s) => s.split(""));
}
Insert cell
Insert cell
Insert cell
function errorScore(syms) {
const stack = new Denque();
for (const sym of syms) {
if (sym == "{" || sym == "(" || sym == "[" || sym == "<") {
stack.push(sym);
} else {
const lastOpen = stack.pop();
if (sym == ")" && lastOpen != "(") {
return 3;
}
if (sym == "]" && lastOpen != "[") {
return 57;
}
if (sym == "}" && lastOpen != "{") {
return 1197;
}
if (sym == ">" && lastOpen != "<") {
return 25137;
}
}
}
return 0;
}
Insert cell
Insert cell
function part1(input) {
return AOC.sum(parse(input).map((s) => errorScore(s)));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function autocompleteScore(syms) {
const stack = new Denque();
const score = (sym) => (sym == "(" ? 1 : sym == "[" ? 2 : sym == "{" ? 3 : 4);
const accScore = (total, sym) => total * 5 + score(sym);

for (const sym of syms) {
sym == "{" || sym == "(" || sym == "[" || sym == "<"
? stack.push(sym)
: stack.pop();
}

return stack.toArray().reverse().reduce(accScore, 0);
}
Insert cell
function part2(input) {
const validLines = parse(input).filter((s) => errorScore(s) == 0);
return AOC.median(validLines.map(autocompleteScore));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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