Created
December 11, 2021 13:59
-
-
Save pengx17/ec0a118f1fba1ab5e10fab4772b86f86 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let raw = `[({(<(())[]>[[{[]{<()<>> | |
| [(()[<>])]({[<{<<[]>>( | |
| {([(<{}[<>[]}>{[]{[(<()> | |
| (((({<>}<{<{<>}{[]{[]{} | |
| [[<[([]))<([[{}[[()]]] | |
| [{[{({}]{}}([{[{{{}}([] | |
| {<[[]]>}<{[{[{[]{()[[[] | |
| [<(<(<(<{}))><([]([]() | |
| <{([([[(<>()){}]>(<<{{ | |
| <{([{{}}[<[[[<>{}]]]>[]]`; | |
| let brackets = [ | |
| ["(", ")"], | |
| ["{", "}"], | |
| ["[", "]"], | |
| ["<", ">"], | |
| ]; | |
| function isLeft(char) { | |
| return brackets.some((b) => b[0] === char); | |
| } | |
| function getLeft(char) { | |
| return brackets.find((b) => b[1] === char)[0]; | |
| } | |
| function getRight(char) { | |
| return brackets.find((b) => b[0] === char)[1]; | |
| } | |
| function fix(chars = []) { | |
| let stack = []; | |
| for (let i = 0; i < chars.length; i++) { | |
| let char = chars[i]; | |
| if (isLeft(char)) { | |
| stack.push(char); | |
| } else { | |
| if (stack.length === 0 || stack.pop() !== getLeft(char)) { | |
| return; | |
| } | |
| } | |
| } | |
| return stack.reverse().map((c) => getRight(c)); | |
| } | |
| const points = { | |
| ")": 1, | |
| "]": 2, | |
| "}": 3, | |
| ">": 4, | |
| }; | |
| function run(input = "") { | |
| let lines = input | |
| .split("\n") | |
| .filter(Boolean) | |
| .map((l) => l.trim().split("")); | |
| let res = lines.map((line) => fix(line)).filter(Boolean); | |
| let scores = res.map((chars) => chars.reduce((a, b) => a * 5 + points[b], 0)); | |
| scores.sort((a, b) => b - a); | |
| console.log(res, scores, scores[(scores.length - 1) / 2]); | |
| } | |
| run(raw); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment