Skip to content

Instantly share code, notes, and snippets.

@mykdavies
Last active November 21, 2023 13:40
Show Gist options
  • Save mykdavies/95d1e587ec0cf63b4cfe987e8a582fbf to your computer and use it in GitHub Desktop.
Save mykdavies/95d1e587ec0cf63b4cfe987e8a582fbf to your computer and use it in GitHub Desktop.
AOC2022 day21
// AOC 2022, Day 21: Monkey Math
// Build a tree
// 1) And visit it.
// 2) And fix the answer.
// https://dartpad.dev/?id=95d1e587ec0cf63b4cfe987e8a582fbf
final ops = {
'+': (num a, num b) => a + b,
'-': (num a, num b) => a - b,
'*': (num a, num b) => a * b,
'/': (num a, num b) => a / b,
};
class Node {
String name;
num _value = 0;
Node(this.name);
bool get isval => true;
// overridden in subclass, so
// ignore: unnecessary_getters_setters
num get value => _value;
set value(num n) => _value = n;
}
class CalcNode extends Node {
late Node left;
late Node right;
late num Function(num, num) op;
CalcNode(super.name);
@override
bool get isval => false;
@override
num get value => op(left.value, right.value);
}
var nodes = <String, Node>{};
buildLines(List<String> lines) {
for (var line in lines) {
var words = line.split(' ');
var name = words[0].replaceAll(':', '');
if (words.length == 2) {
nodes[name] = Node(name)..value = int.parse(words[1]);
} else {
nodes[name] = CalcNode(name)
..left = Node(words[1])
..op = ops[words[2]]!
..right = Node(words[3]);
}
}
connectNodes();
}
connectNodes() {
for (var n in nodes.values.where((e) => !e.isval)) {
(n as CalcNode)
..left = nodes[n.left.name]!
..right = nodes[n.right.name]!;
}
}
part1(List<String> lines) {
buildLines(lines);
return nodes['root']!.value;
}
part2(List<String> lines) {
buildLines(lines);
// Let the network calculate the answer for us :-)
var root = nodes['root']! as CalcNode..op = ops['-']!;
var humn = nodes['humn']!..value = 0;
var v1 = root.value;
humn.value = 10000000000; // just need to make it big enough...
var v2 = root.value;
return v1 * humn.value ~/ (v1 - v2);
}
var testdata = [
"root: pppw + sjmn",
"dbpl: 5",
"cczh: sllz + lgvd",
"zczc: 2",
"ptdq: humn - dvpt",
"dvpt: 3",
"lfqf: 4",
"humn: 5",
"ljgn: 2",
"sjmn: drzm * dbpl",
"sllz: 4",
"pppw: cczh / lfqf",
"lgvd: ljgn * ptdq",
"drzm: hmdt - zczc",
"hmdt: 32"
];
void main(List<String> args) {
var dt = DateTime.now();
assert(part1(testdata) == 152);
assert(part2(testdata) == 301);
var rt = DateTime.now().difference(dt).inMilliseconds;
print('tests succeeded in $rt ms');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment