From 68615a9ad2c942254135cffb00cf25a84a3b1356 Mon Sep 17 00:00:00 2001 From: Prefetch Date: Sat, 31 Dec 2022 22:21:39 +0100 Subject: Initial commit --- 07/main.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100755 07/main.py (limited to '07/main.py') 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() -- cgit v1.2.3