Files
aocpy/2024/d9.py
2024-12-09 01:11:22 -05:00

107 lines
2.3 KiB
Python

from lib import get_data
from lib import Grid2D
from lib import ints
from itertools import combinations
from collections import defaultdict
from copy import deepcopy
data = get_data(__file__)
i = 0
f = True
d = []
spaces = 0
for c in data.strip():
if f:
d.append([int(c), i, f])
f = False
i += 1
else:
spaces += int(c)
d.append([int(c), -1, f])
f = True
d2 = deepcopy(d)
BLOCKS, ID, FULL = 0, 1, 2
empty_i = 1
full_i = len(d) - 1
assert d[full_i][FULL]
while empty_i < full_i:
empty = d[empty_i]
full = d[full_i]
if empty[BLOCKS] == full[BLOCKS]:
empty[ID] = full[ID]
empty[FULL] = True
full[BLOCKS] = 0
full[FULL] = False
elif empty[BLOCKS] < full[BLOCKS]:
empty[ID] = full[ID]
empty[FULL] = True
full[BLOCKS] -= empty[BLOCKS]
elif empty[BLOCKS] > full[BLOCKS]:
new = [empty[BLOCKS] - full[BLOCKS], empty[ID], False]
empty[ID] = full[ID]
empty[BLOCKS] = full[BLOCKS]
empty[FULL] = True
d.insert(empty_i + 1, new)
full_i += 1
full[BLOCKS] = 0
full[FULL] = False
else:
assert False
while d[empty_i][FULL] == True:
empty_i += 1
while d[full_i][FULL] == False:
full_i -= 1
t = 0
i = 0
for b in d:
if b[FULL] == False:
break
for _ in range(b[BLOCKS]):
t += i * b[ID]
i += 1
print(t)
d = d2
full_i = len(d) - 1
while full_i > 0:
full = d[full_i]
prev_i = full_i
for empty_i in range(0, full_i):
empty = d[empty_i]
if full[FULL] == False:
continue
if empty[FULL]:
continue
if empty[BLOCKS] < full[BLOCKS]:
continue
if empty[BLOCKS] == full[BLOCKS]:
empty[FULL] = True
empty[ID] = full[ID]
full[FULL] = False
elif empty[BLOCKS] > full[BLOCKS]:
full[FULL] = False
new = [full[BLOCKS], full[ID], True]
d[empty_i] = new
d.insert(empty_i + 1, [empty[BLOCKS] - full[BLOCKS], -1, False])
full_i += 1
break
full_i -= 1
t = 0
i = 0
for b in d:
for _ in range(b[BLOCKS]):
if b[FULL] == True:
t += i * b[ID]
i += 1
print(t)