summary refs log tree commit diff stats
path: root/day7.py
diff options
context:
space:
mode:
Diffstat (limited to 'day7.py')
-rw-r--r--day7.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/day7.py b/day7.py
new file mode 100644
index 0000000..3c7f0c3
--- /dev/null
+++ b/day7.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+
+from functools import cache
+from collections import defaultdict
+import operator
+
+ops = {
+    'EQ': lambda x: x,
+    'NOT': lambda x: ~x & 0xffff,
+    'AND': operator.iand,
+    'OR': operator.ior,
+    'RSHIFT': operator.rshift,
+    'LSHIFT': operator.lshift
+}
+
+wires = defaultdict(list)
+with open('day7.txt') as data:
+    for line in data:
+        calc, target = line.strip().split(' -> ')
+        calc = calc.split()
+        if len(calc) == 1:
+            wires[target] = ('EQ', calc[0])
+        elif len(calc) == 2:
+            wires[target] = (calc[0], calc[1])
+        else:
+            wires[target] = (calc[1], calc[0], calc[2])
+
+@cache
+def get_value(key):
+    try:
+        return int(key)
+    except ValueError:
+        pass
+
+    op, *value = wires[key]
+
+    if len(value) == 1:
+        return ops[op](get_value(value[0]))
+    else:
+        return ops[op](get_value(value[0]), get_value(value[1]))
+
+# part 1
+print(get_value('a'))
+
+# part 2
+get_value.cache_clear()
+
+wires['b'] = ('EQ', 3176)
+print(get_value('a'))