Spaces:
Running
Running
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.") |