Dag 14 i Python
lines = open('input14.txt', 'rt').read().split('\n')
pattern0 = tuple(tuple(l) for l in lines)
H = len(pattern0)
W = len(pattern0[0])
def tilt_north(pattern):
mutable_pattern = [list(l) for l in pattern]
for y in range(1, H):
for x in range(W):
if mutable_pattern[y][x] == 'O':
new_y = y
for y2 in range(y-1, -1, -1):
if mutable_pattern[y2][x] == '.':
new_y = y2
else:
break
if new_y != y:
mutable_pattern[y][x] = '.'
mutable_pattern[new_y][x] = 'O'
return tuple(tuple(l) for l in mutable_pattern)
def rotate_90(pattern):
return tuple(tuple(pattern[H - 1 - x][y] for x in range(W)) for y in range(H))
period = 0
offset = 0
patterns = {}
pattern = pattern0
N = 1000000000
for spins in range(1, N):
for _ in range(4):
pattern = tilt_north(pattern)
pattern = rotate_90(pattern)
last_occurrence = patterns.get(pattern)
if last_occurrence is not None:
period = spins - last_occurrence
offset = spins
break
patterns[pattern] = spins
patterns = ((i, t) for t, i in patterns.items())
patterns = [t for _, t in sorted(patterns)]
patterns = patterns[-period:]
def calculate_load(pattern):
return sum(sum(c == 'O' for c in row) * (H - y) for y, row in enumerate(pattern))
pattern_index = (N - offset) % period
pattern = patterns[pattern_index]
print(calculate_load(pattern))