83 lines
2.8 KiB
Python
83 lines
2.8 KiB
Python
import copy
|
|
|
|
|
|
f = open('input.txt', 'r')
|
|
# f = open('test.txt', 'r')
|
|
# f = open('test2.txt', 'r')
|
|
content = f.read()
|
|
lines = content.splitlines()
|
|
modules = {}
|
|
|
|
for line in lines:
|
|
parts = line.split(" -> ")
|
|
outputs = parts[1].replace(" ", "").split(",")
|
|
|
|
if "%" == parts[0][0]:
|
|
modules[parts[0][1:]] = {"type": parts[0][0], "state": False, "outputs": outputs}
|
|
elif "&" == parts[0][0]:
|
|
modules[parts[0][1:]] = {"type": parts[0][0], "in_states": {}, "outputs": outputs}
|
|
else:
|
|
modules[parts[0]] = {"type": "", "outputs": outputs}
|
|
|
|
for mod in modules:
|
|
for i in modules[mod]["outputs"]:
|
|
if i in modules and modules[i]["type"] == "&":
|
|
modules[i]["in_states"][mod] = False
|
|
|
|
ins = [{"too": "broadcaster", "from": "button", "signal": "low"}]
|
|
outs = []
|
|
|
|
low_pulses = 0
|
|
high_pulses = 0
|
|
|
|
for button_presses in range(1000000):
|
|
ins = [{"too": "broadcaster", "from": "button", "signal": "low"}]
|
|
while len(ins) != 0:
|
|
# print(ins)
|
|
# print(modules)
|
|
outs = []
|
|
for line in ins:
|
|
if line["signal"] == "low":
|
|
low_pulses += 1
|
|
elif line["signal"] == "high":
|
|
high_pulses += 1
|
|
|
|
if line["too"] == "rx" and line["signal"] == "low":
|
|
out = []
|
|
print(button_presses)
|
|
break
|
|
|
|
if line["too"] not in modules: continue
|
|
|
|
if modules[line["too"]]["type"] == "":
|
|
for out in modules[line["too"]]["outputs"]:
|
|
outs.append({"too": out, "from": line["too"], "signal": line["signal"]})
|
|
|
|
elif modules[line["too"]]["type"] == "%":
|
|
if line["signal"] == "low":
|
|
modules[line["too"]]["state"] = not modules[line["too"]]["state"]
|
|
sig = "high" if modules[line["too"]]["state"] else "low"
|
|
for out in modules[line["too"]]["outputs"]:
|
|
outs.append({"too": out, "from": line["too"], "signal": sig})
|
|
|
|
elif modules[line["too"]]["type"] == "&":
|
|
modules[line["too"]]["in_states"][line["from"]] = line["signal"] == "high"
|
|
all_states_high = True
|
|
for state in modules[line["too"]]["in_states"]:
|
|
if modules[line["too"]]["in_states"][state] != True:
|
|
all_states_high = False
|
|
break
|
|
sig = "low" if all_states_high else "high"
|
|
for out in modules[line["too"]]["outputs"]:
|
|
outs.append({"too": out, "from": line["too"], "signal": sig})
|
|
ins = copy.deepcopy(outs)
|
|
|
|
|
|
|
|
|
|
|
|
print(low_pulses*high_pulses)
|
|
print(low_pulses, high_pulses)
|
|
|
|
f.close()
|