Solve 2024 day 9

This commit is contained in:
felixm 2024-12-09 01:11:22 -05:00
parent b747d3973a
commit 2a10543852
2 changed files with 107 additions and 0 deletions

106
2024/d9.py Normal file
View 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)

View File

@ -299,4 +299,5 @@ and focus. Of course, learning more algorithms and techniques helps.
- Day 6: `00:09:43 1082 0 00:16:29 464 0` - Day 6: `00:09:43 1082 0 00:16:29 464 0`
- Day 7: `00:12:29 2058 0 00:13:08 1170 0` - Day 7: `00:12:29 2058 0 00:13:08 1170 0`
- Day 8: `00:15:59 1742 0 00:26:56 2190 0` - Day 8: `00:15:59 1742 0 00:26:56 2190 0`
- Day 9: `00:48:23 6055 0 01:09:38 3159 0`