diff options
author | Julien Dessaux | 2022-12-31 17:04:04 +0100 |
---|---|---|
committer | Julien Dessaux | 2022-12-31 17:33:31 +0100 |
commit | 7a7a788a11c0f6508837a32c4332545870eca653 (patch) | |
tree | 9935c154ae6ba2f10dc55fa95e919f5a1628ee67 /2022/21-Monkey-Math/first.js | |
parent | 2022-20 in js (diff) | |
download | advent-of-code-7a7a788a11c0f6508837a32c4332545870eca653.tar.gz advent-of-code-7a7a788a11c0f6508837a32c4332545870eca653.tar.bz2 advent-of-code-7a7a788a11c0f6508837a32c4332545870eca653.zip |
2022-21 part 1 in js
Diffstat (limited to '')
-rw-r--r-- | 2022/21-Monkey-Math/first.js | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/2022/21-Monkey-Math/first.js b/2022/21-Monkey-Math/first.js new file mode 100644 index 0000000..b6da414 --- /dev/null +++ b/2022/21-Monkey-Math/first.js @@ -0,0 +1,45 @@ +import * as fs from "fs"; + +const simple = /(\w+): (\d+)/; +const operation = /(\w+): (\w+) ([+\-*/]) (\w+)/; + +function load(filename) { + let res = {}; + fs.readFileSync(filename, "utf8") + .trim() + .split("\n") + .forEach(line => { + const s = line.match(simple); + if (s) { + res[s[1]] = function() { return parseInt(s[2]); }; + } else { + const o = line.match(operation); + res[o[1]] = function () { + let left = res[o[2]](); + let right = res[o[4]](); + switch(o[3]) { + case "+": return left + right; + case "-": return left - right; + case "*": return left * right; + case "/": return left / right; + } + }; + } + }); + return res; +} + +let example = load("example"); +let input = load("input"); + +function solve(input) { + return input["root"](); +} + +const exampleOutput = solve(example); +if (exampleOutput !== 152) { + console.log("Example failed with " + exampleOutput); + process.exit(1); // eslint-disable-line +} + +console.log(solve(input)); |