From 08b4e30a3a74a029d785edf4f18b7f7d856169e3 Mon Sep 17 00:00:00 2001 From: Julia Lange Date: Tue, 10 Dec 2024 10:25:50 -0800 Subject: [PATCH] 2024 Dec 09th --- Python/2024/09/main.py | 66 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 Python/2024/09/main.py diff --git a/Python/2024/09/main.py b/Python/2024/09/main.py new file mode 100644 index 0000000..fbb4073 --- /dev/null +++ b/Python/2024/09/main.py @@ -0,0 +1,66 @@ +input = open("input", 'r').read().strip() + +# d = [int(line) for line in input] +d = {id: int(line) for id, line in enumerate(input)} + +def entry(pos, id, length): + return {"pos": pos, "id": id, "length": length} +pos = 0 +s = [] +e = [] +for id, leng in d.items(): + if leng <= 0: + continue + if id % 2 == 0: + s.append(entry(pos, id // 2, leng)) + else: + e.append(entry(pos, -1, leng)) + pos += leng + +# print(d) + +def run(): + start = 0 + end = len(d) - 1 + if end % 2 != 0: + end -= 1 + pos = 0 + checksum = 0 + + while start <= end: + if start % 2 == 0: # Full + checksum += pos * (start // 2) + pos += 1 + d[start] -= 1 + while d[start] == 0: + start += 1 + else: # Empty + checksum += pos * (end // 2) + pos += 1 + d[start] -= 1 + while d[start] == 0: + start += 1 + d[end] -= 1 + while d[end] == 0: + end -= 2 + return checksum + +def run2(): + # a = s[-1] + # print(a) + for file in reversed(s): + for empty in e: + if empty['length'] >= file['length'] and file['pos'] > empty['pos']: + file['pos'] = empty['pos'] + empty['pos'] += file['length'] + empty['length'] = empty['length'] - file['length'] + break + + checksum = sum([ + sum([(file['pos']+i) * file['id'] for i in range(file['length'])]) for file in s + ]) + return checksum + + +print(run()) +print(run2())