From 484491426db20b1e0496b28afa3d8accb14c640f Mon Sep 17 00:00:00 2001 From: Andrew Ekstedt Date: Mon, 9 Dec 2024 17:46:27 +0000 Subject: [PATCH] day 9 part 2 it seemed easier to go for a sparse implementation than try to make the dense implementation from part 1 work --- day09/sol.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/day09/sol.py b/day09/sol.py index 9297f42..7a5e8c7 100644 --- a/day09/sol.py +++ b/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)