Optimized day 16

master
Tibor Bizjak 2023-03-20 18:37:27 +01:00
parent a6ac23f5c7
commit 8c27fca769
1 changed files with 23 additions and 18 deletions

View File

@ -1,8 +1,5 @@
#!/usr/bin/env python3
from intcode import defaultlist
from operator import mul
def str_of_signal(signal):
return ''.join(map(str, signal))
@ -12,32 +9,40 @@ def apply_pattern(signal, offset=0):
for i in range(len(signal)-2, -1, -1):
sums[i] = sums[i+1] + signal[i]
sums = defaultlist(sums, lambda : 0)
new = []
for i in range(len(signal)):
step = i + offset + 1
n = 0
for block in range(i, len(signal), 4*step):
n += sums[block] - sums[block + step]
n -= sums[block + 2*step] - sums[block + 3*step]
new.append(abs(n)%10)
return new
i = 0
step = offset + 1
while i + step < len(signal):
n = sum(sums[i::4*step])
n -= sum(sums[i+step::4*step])
n -= sum(sums[i+2*step::4*step])
n += sum(sums[i+3*step::4*step])
signal[i] = abs(n)%10
i += 1
step += 1
signal[i:] = [s % 10 for s in sums[i:]]
def phase(signal, n, offset=0):
signal = signal[offset:]
for i in range(n):
signal = apply_pattern(signal, offset)
return signal
apply_pattern(signal, offset)
def preproc(puzzle_input):
return list(map(int, puzzle_input))
def partI(signal):
return str_of_signal(phase(signal, 100)[:8])
signal = signal.copy()
phase(signal, 100)
return str_of_signal(signal[:8])
def partII(signal):
signal = signal * 10**4
offset = int(str_of_signal(signal[:7]))
return str_of_signal(phase(signal, 100, offset)[:8])
signal = signal[offset:]
phase(signal, 100, offset)
return str_of_signal(signal[:8])