Spaces:
Running
Running
File size: 1,285 Bytes
a4da721 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
def evaluate_wire(wire, circuit, cache):
if wire in cache:
return cache[wire]
if isinstance(circuit[wire], int):
cache[wire] = circuit[wire]
return circuit[wire]
op, in1, in2 = circuit[wire]
val1 = evaluate_wire(in1, circuit, cache)
val2 = evaluate_wire(in2, circuit, cache)
if op == "AND":
result = val1 * val2
elif op == "OR":
result = val1 | val2
elif op == "XOR":
result = val1 ^ val2
cache[wire] = result
return result
with open("./input.txt", "r") as f:
lines = f.readlines()
circuit = {}
for line in lines:
line = line.strip()
if ":" in line:
wire, val = line.split(":")
circuit[wire.strip()] = int(val.strip())
elif "->" in line:
parts = line.split("->")
inputs, output = parts[0].strip(), parts[1].strip()
op, in1, in2 = inputs.split()
circuit[output] = (op, in1, in2)
cache = {}
z_values = []
for i in range(14):
z_values.append(str(evaluate_wire(f"z{i:02}", circuit, cache)))
result1 = int("".join(z_values), 2)
print(result1)
# Part 2 requires reverse-engineering the specific circuit logic and cannot be solved generically.
print("Part 2 requires manual analysis of the circuit and cannot be automated easily.") |