summaryrefslogtreecommitdiff
path: root/07/main.py
diff options
context:
space:
mode:
authorPrefetch2022-12-31 22:21:39 +0100
committerPrefetch2022-12-31 22:21:39 +0100
commit68615a9ad2c942254135cffb00cf25a84a3b1356 (patch)
tree1ed3131f673207b2ef0bdaee3ee98bb68d6640ca /07/main.py
Initial commit
Diffstat (limited to '07/main.py')
-rwxr-xr-x07/main.py61
1 files changed, 61 insertions, 0 deletions
diff --git a/07/main.py b/07/main.py
new file mode 100755
index 0000000..7babff9
--- /dev/null
+++ b/07/main.py
@@ -0,0 +1,61 @@
+#!/usr/bin/python
+
+
+
+def eval_wire(wires, w):
+ # Shortcut for cleaner code
+ if w.isdigit():
+ return int(w) & 65535
+
+ result = 0
+ tokens = wires[w]
+
+ if len(tokens) == 1:
+ result = eval_wire(wires, tokens[0])
+
+ if len(tokens) == 2:
+ if tokens[0] == "NOT":
+ result = ~eval_wire(wires, tokens[1])
+
+ if len(tokens) == 3:
+ if tokens[1] == "AND":
+ result = eval_wire(wires, tokens[0]) & eval_wire(wires, tokens[2])
+ if tokens[1] == "OR":
+ result = eval_wire(wires, tokens[0]) | eval_wire(wires, tokens[2])
+ if tokens[1] == "LSHIFT":
+ result = eval_wire(wires, tokens[0]) << eval_wire(wires, tokens[2])
+ if tokens[1] == "RSHIFT":
+ result = eval_wire(wires, tokens[0]) >> eval_wire(wires, tokens[2])
+
+ result &= 65535
+ wires[w] = [str(result)] # cache result
+ return int(result)
+
+
+
+def solve_partn(partn, lines):
+ # Parse input into a marginally nicer form
+ wires = {}
+ for line in lines:
+ words = line.split(" ")
+ wires[words[-1]] = words[0 : -2]
+
+ if partn == 2:
+ wires["b"] = ["46065"]
+
+ return eval_wire(wires, "a")
+
+
+
+def main():
+ # Read wire configuration from input text file
+ with open("input.txt", "r") as f:
+ lines = f.read().splitlines()
+
+ print("Part 1 solution:", solve_partn(1, lines)) # 46065 for me
+ print("Part 2 solution:", solve_partn(2, lines)) # 14134 for me
+
+
+
+if __name__ == "__main__":
+ main()