adventofcode/2021/10/part2.mjs

43 lines
842 B
JavaScript
Raw Normal View History

2021-12-10 17:39:02 +00:00
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
2021-12-10 18:39:15 +00:00
import * as p1 from "./part1.mjs";
2021-12-10 17:39:02 +00:00
2021-12-10 18:35:49 +00:00
function completionString(line) {
const stack = [];
2021-12-10 18:39:15 +00:00
for (const c of line) {
if (p1.closing[c]) {
2021-12-10 18:35:49 +00:00
stack.unshift(p1.closing[c]);
2021-12-10 18:39:15 +00:00
} else if (c !== stack.shift()) {
return;
2021-12-10 18:35:49 +00:00
}
}
return stack;
}
export function linesScore(lines) {
2021-12-10 18:39:15 +00:00
lines = lines.map(completionString).filter((x) => x);
2021-12-10 18:35:49 +00:00
const points = {
2021-12-10 18:39:15 +00:00
")": 1,
"]": 2,
"}": 3,
">": 4,
};
2021-12-10 18:35:49 +00:00
2021-12-10 18:39:15 +00:00
const lineScore = (line) => line.reduce((a, b) => 5 * a + points[b], 0);
2021-12-10 18:35:49 +00:00
return lines.map(lineScore);
}
export function solution(lines) {
2021-12-10 18:39:15 +00:00
const scores = linesScore(lines);
2021-12-10 18:35:49 +00:00
2021-12-10 18:39:15 +00:00
scores.sort((a, b) => (a < b ? -1 : 1));
2021-12-10 18:35:49 +00:00
2021-12-10 18:39:15 +00:00
return scores[(scores.length - 1) / 2];
2021-12-10 17:39:02 +00:00
}