77 lines
2.5 KiB
Python
77 lines
2.5 KiB
Python
with open('puzzle.txt', 'r') as f:
|
|
instructions = f.read().splitlines()
|
|
|
|
import operator
|
|
|
|
wire_dict = {}
|
|
|
|
useful_instructions = []
|
|
|
|
# thanks chatgpt
|
|
operations = {
|
|
"RSHIFT": operator.rshift,
|
|
"LSHIFT": operator.lshift,
|
|
"NOT": lambda x: ~x,
|
|
"AND": operator.and_,
|
|
"OR": operator.or_
|
|
}
|
|
# end thanks chatgpt
|
|
|
|
for instruction in instructions:
|
|
instruction = instruction.split(' ')
|
|
useful_instructions.append(instruction[::-1])
|
|
|
|
while len(useful_instructions) > 0:
|
|
for instruction in useful_instructions:
|
|
output = instruction[0]
|
|
|
|
input_a = instruction[2]
|
|
|
|
if len(instruction) == 3:
|
|
if input_a.isdigit():
|
|
input_a = int(input_a)
|
|
wire_dict.update({output: int(input_a)})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
elif input_a in wire_dict.keys() and output not in wire_dict.keys():
|
|
wire_dict.update({output: wire_dict[input_a]})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
elif len(instruction) == 4:
|
|
operator = instruction[3]
|
|
|
|
if input_a in wire_dict.keys():
|
|
wire_dict.update({output: operations[operator](wire_dict[input_a])})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
elif len(instruction) == 5:
|
|
operator = instruction[3]
|
|
input_b = instruction[4]
|
|
|
|
if input_a.isdigit():
|
|
if input_b.isdigit():
|
|
wire_dict.update({output: operations[operator](int(input_b), int(input_a))})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
elif input_b in wire_dict.keys():
|
|
wire_dict.update({output: operations[operator](wire_dict[input_b], int(input_a))})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
elif input_b.isdigit():
|
|
if input_a in wire_dict.keys():
|
|
wire_dict.update({output: operations[operator](int(input_b), wire_dict[input_a])})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
else:
|
|
if input_a in wire_dict.keys() and input_b in wire_dict.keys():
|
|
wire_dict.update({output: operations[operator](wire_dict[input_b], wire_dict[input_a])})
|
|
useful_instructions.remove(instruction)
|
|
break
|
|
|
|
print(wire_dict['a']) |