aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorClyne Sullivan <clyne@bitgloo.com>2022-12-22 08:53:56 -0500
committerClyne Sullivan <clyne@bitgloo.com>2022-12-22 08:53:56 -0500
commit43d25346d7cd339327c218376fa785a3a4b3781d (patch)
tree88f3398f14be89b3f37d74a30889551b4170c5a1
parentd58977fe0f11cabbd979167fd87f88c1748abc6a (diff)
add day 21
-rw-r--r--day21/part1.cpp83
-rw-r--r--day21/part2.md9
2 files changed, 92 insertions, 0 deletions
diff --git a/day21/part1.cpp b/day21/part1.cpp
new file mode 100644
index 0000000..5698c82
--- /dev/null
+++ b/day21/part1.cpp
@@ -0,0 +1,83 @@
+#include <cctype>
+#include <iostream>
+#include <map>
+#include <string>
+#include <vector>
+
+struct Node
+{
+ std::string left;
+ std::string right;
+ char op = 0;
+ long long n = 0;
+
+ bool solved() const { return left.empty(); }
+
+ bool solve(const auto& tree) {
+ const auto& ln = tree.at(left);
+ const auto& rn = tree.at(right);
+
+ if (ln.solved() && rn.solved()) {
+ switch (op) {
+ case '+':
+ n = ln.n + rn.n;
+ break;
+ case '-':
+ n = ln.n - rn.n;
+ break;
+ case '*':
+ n = ln.n * rn.n;
+ break;
+ case '/':
+ n = ln.n / rn.n;
+ break;
+ }
+
+ left.clear();
+ }
+
+ return solved();
+ }
+};
+
+int main()
+{
+ std::map<std::string, Node> tree;
+
+ while (!std::cin.eof()) {
+ std::string line;
+ std::getline(std::cin, line);
+ if (std::cin.eof())
+ break;
+
+ auto split = line.find(':');
+ const auto key = line.substr(0, split);
+ line = line.substr(split + 2);
+
+ Node node;
+ if (isdigit(line.front())) {
+ node.n = std::stoll(line);
+ } else {
+ split = line.find(' ');
+ node.left = line.substr(0, split);
+ node.op = line.at(split + 1);
+ node.right = line.substr(split + 3, 4);
+ }
+
+ tree.emplace(key, node);
+ }
+
+ bool more = true;
+ while (more) {
+ more = false;
+ for (auto& [k, v] : tree) {
+ if (!v.solved())
+ more |= !v.solve(tree);
+ }
+ }
+
+ std::cout << "root: " << tree["root"].n << std::endl;
+
+ return 0;
+}
+
diff --git a/day21/part2.md b/day21/part2.md
new file mode 100644
index 0000000..957e3da
--- /dev/null
+++ b/day21/part2.md
@@ -0,0 +1,9 @@
+## Solving part 2 with Maxima
+
+1. Add '$' to the end of each line of input.
+2. Replace `root`'s operator with '='.
+3. Replace `humn`'s definition with x: `humn: x$`.
+4. Load into maxima: `maxima --init-mac=input`
+5. Evaluate `root` until `x` is visible: `root: root, eval;`.
+6. Solve: `solve(root, x)`.
+