Dag 20, Python
Okej den här var plågsam. Först när jag visualiserade grafen så kunde jag se hur jag skulle lösa uppgiften.
lines = open('input20.txt', 'rt').read().split('\n')
module_kind = {}
module_targets = {}
for l in lines:
a, b = l.split(' -> ')
targets = b.split(', ')
if a == 'broadcaster':
kind, name = 'b', a
else:
kind, name = a[0], a[1:]
module_kind[name] = kind
module_targets[name] = targets
def get_initial_memory():
memory = {}
for name, kind in module_kind.items():
if kind == '%':
memory[name] = 0
elif kind == '&':
memory[name] = {}
for name, targets in module_targets.items():
for target in targets:
kind = module_kind.get(target)
if kind == '&':
memory[target][name] = 0
return memory
def process_pulses(pulses, memory):
while pulses:
sender, level, name = pulses.pop(0)
kind = module_kind.get(name)
targets = module_targets.get(name)
if kind == 'b':
for target in targets:
pulses.append((name, level, target))
elif kind == '%':
if level == 0:
level = memory.get(name, 0) ^ 1
memory[name] = level
for target in targets:
pulses.append((name, level, target))
elif kind == '&':
if level == 1 and 'rx' in targets:
return True
mem = memory.get(name, {})
mem[sender] = level
level = 0 if all(x == 1 for x in mem.values()) else 1
for target in targets:
pulses.append((name, level, target))
return False
prod = 1
for n in module_targets['broadcaster']:
memory = get_initial_memory()
steps = 0
while True:
steps += 1
pulses = [('broadcaster', 0, n)]
if process_pulses(pulses, memory):
prod *= steps
break
print(prod)