commit 93f9d02e978d10b4ff02ac029b6a6eff3d3193cf
parent a299e1723f0a700a892720badab2e06a202d1eda
Author: Sebastiano Tronto <sebastiano@tronto.net>
Date: Mon, 9 Dec 2024 06:36:25 +0100
Day 9 2024
Diffstat:
3 files changed, 102 insertions(+), 0 deletions(-)
diff --git a/2024/09/Makefile b/2024/09/Makefile
@@ -0,0 +1,24 @@
+CC=g++ -std=c++20 -g -Wall
+
+a:
+ ${CC} -o a.out day09a.cpp
+
+b:
+ ${CC} -o b.out day09b.cpp
+
+clean:
+ rm -f a b
+
+atest: a
+ ./a.out
+
+btest: b
+ ./b.out
+
+arun: a
+ ./a.out < input
+
+brun: b
+ ./b.out < input
+
+.PHONY: a b clean atest btest arun brun
diff --git a/2024/09/day09a.cpp b/2024/09/day09a.cpp
@@ -0,0 +1,32 @@
+#include <algorithm>
+#include <iostream>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
+using namespace std;
+
+int main() {
+ vector<long long> a;
+ char c;
+ for (int id = 0; cin >> c; id++)
+ for (int j = 0; j < c-'0'; j++)
+ a.push_back(id % 2 == 0 ? id/2 : -1); // -1 = space
+
+ int j = 0;
+ for (int i = a.size()-1; i >= 0; i--) {
+ while (a[j] >= 0) j++;
+ if (a[j] == -2) break;
+ a[j] = a[i];
+ a[i] = -2; // -2 = freed up
+ }
+
+ long long checksum = 0;
+ for (long long i = 0; i < (long long)a.size() && a[i] != -2; i++)
+ checksum += i*a[i];
+ cout << checksum << endl;
+
+ return 0;
+}
diff --git a/2024/09/day09b.cpp b/2024/09/day09b.cpp
@@ -0,0 +1,46 @@
+#include <algorithm>
+#include <iostream>
+#include <map>
+#include <set>
+#include <sstream>
+#include <string>
+#include <string_view>
+#include <vector>
+using namespace std;
+
+int main() {
+ vector<long long> a;
+ vector<pair<int, int>> freesp, file;
+ char c;
+ for (int id = 0; cin >> c; id++) {
+ if (id % 2 == 1)
+ freesp.push_back(make_pair(a.size(), c-'0'));
+ else
+ file.push_back(make_pair(a.size(), c-'0'));
+ for (int j = 0; j < c-'0'; j++)
+ a.push_back(id % 2 == 0 ? id/2 : -1); // -1 = space
+ }
+
+ for (int i = file.size()-1; i >= 0; i--) {
+ for (auto& f : freesp) {
+ if (f.first >= file[i].first) break;
+ if (f.second >= file[i].second) {
+ for (int k = 0; k < file[i].second; k++) {
+ a[f.first+k] = a[file[i].first+k];
+ a[file[i].first+k] = -2;
+ }
+ f.first += file[i].second;
+ f.second -= file[i].second;
+ break;
+ }
+ }
+ }
+
+ long long checksum = 0;
+ for (long long i = 0; i < (long long)a.size(); i++)
+ if (a[i] >= 0)
+ checksum += i*a[i];
+ cout << checksum << endl;
+
+ return 0;
+}