Solve 2024 day 9
This commit is contained in:
parent
b747d3973a
commit
2a10543852
106
2024/d9.py
Normal file
106
2024/d9.py
Normal file
@ -0,0 +1,106 @@
|
||||
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)
|
Loading…
Reference in New Issue
Block a user