From 72e85ca4f788c530ac4983af0e7f2b70202e324e Mon Sep 17 00:00:00 2001 From: setop Date: Mon, 9 Dec 2024 09:46:07 +0100 Subject: [PATCH] day 9, pure compute, good candidate for compier: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * python: 2.525 s ± 0.169 s * pypy: 175.0 ms ± 8.9 ms 14x * codon: 29.3 ms ± 7.9 ms 87x --- d09/part1.py | 36 ++++++++++++++++++++++++++++++++++++ d09/part2.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 d09/part1.py create mode 100644 d09/part2.py diff --git a/d09/part1.py b/d09/part1.py new file mode 100644 index 0000000..3b3edc3 --- /dev/null +++ b/d09/part1.py @@ -0,0 +1,36 @@ +import sys, os + +I = list(map(int, sys.stdin.read().strip())) + +def sum_n(a, b): + return (b-a+1)*(a+b)//2 + +I = I +j = 0 +b = 0 +res = 0 +id = len(I)//2 # last ID +x = I[len(I)-1] +for i in range(len(I)//2): + if len(I)-2*j-1 - 2*i == 0: + res += sum_n(b, b+x-1)*i + break + nb = b + I[2*i] + res += sum_n(b, nb-1)*i + b = nb + space = I[2*i+1] + while space > 0: + if x > space: + nb = b + space + res += sum_n(b, nb-1)*id + x -= space + space = 0 + else: + nb = b + x + res += sum_n(b, nb-1)*id + id -= 1 + space -= x + j += 1 + x = I[len(I)-2*j-1] + b = nb +print(res) diff --git a/d09/part2.py b/d09/part2.py new file mode 100644 index 0000000..f136816 --- /dev/null +++ b/d09/part2.py @@ -0,0 +1,30 @@ +import sys, os + +I = list(map(int, sys.stdin.read().strip())) + +def sum_n(a, b): + return (b-a+1)*(a+b)//2 + +idxs = [] +b = 0 +for i in I: + idxs.append(b) + b += i + +res = 0 +id = len(I)//2 # last id +for j in range(len(I)-1,-1,-2): # backward + fsize = I[j] + for i in range(1, j, 2): # find free space forward + if I[i] >= fsize: # enough free space + b = idxs[i] + res += sum_n(b, b+fsize-1)*id + idxs[i] += fsize + I[i] -= fsize + break + else: # block too big stays where it is + b = idxs[j] + res += sum_n(b, b+fsize-1)*id + id -= 1 + +print(res)