day 9 part 2
it seemed easier to go for a sparse implementation than try to make the dense implementation from part 1 workmain
parent
f0eff608ae
commit
484491426d
40
day09/sol.py
40
day09/sol.py
|
@ -40,6 +40,46 @@ def solve(input):
|
|||
t += i*x
|
||||
print(t)
|
||||
|
||||
def solve2(input):
|
||||
freelist = []
|
||||
blocks = {}
|
||||
pos = 0
|
||||
id = 0
|
||||
for i in range(len(input)):
|
||||
n = int(input[i])
|
||||
if i % 2 == 0:
|
||||
blocks[id] = (pos, n)
|
||||
id += 1
|
||||
else:
|
||||
freelist.append((pos, n))
|
||||
pos += n
|
||||
|
||||
lastid = id
|
||||
for id in range(lastid-1,-1,-1):
|
||||
bpos, blen = blocks[id]
|
||||
for i in range(len(freelist)):
|
||||
fpos, flen = freelist[i]
|
||||
if bpos < fpos:
|
||||
break
|
||||
if blen <= flen:
|
||||
blocks[id] = (fpos, blen)
|
||||
if flen == blen:
|
||||
del freelist[i]
|
||||
else:
|
||||
freelist[i] = (fpos+blen, flen-blen)
|
||||
break
|
||||
|
||||
t = 0
|
||||
for id in blocks:
|
||||
i, n = blocks[id]
|
||||
for x in range(i,i+n):
|
||||
t += id*x
|
||||
|
||||
print(t)
|
||||
|
||||
|
||||
solve(sample)
|
||||
solve(input)
|
||||
|
||||
solve2(sample)
|
||||
solve2(input)
|
||||
|
|
Loading…
Reference in New Issue