From 9a1f073f8e33e8b0d6c97332f51161683cfc6e58 Mon Sep 17 00:00:00 2001 From: Sebastiano Tronto Date: Mon, 9 Dec 2024 14:06:37 +0100 Subject: Day 9 with views::reverse --- 2024/09/day09a.cpp | 7 ++++--- 2024/09/day09b.cpp | 17 +++++++++-------- 2024/learned.txt | 1 + 2024/template.cpp | 1 + 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/2024/09/day09a.cpp b/2024/09/day09a.cpp index c52c8f0..80732d7 100644 --- a/2024/09/day09a.cpp +++ b/2024/09/day09a.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -16,11 +17,11 @@ int main() { a.push_back(id % 2 == 0 ? id/2 : -1); // -1 = space int j = 0; - for (int i = a.size()-1; i >= 0; i--) { + for (auto& x : a | views::reverse) { while (a[j] >= 0) j++; if (a[j] == -2) break; - a[j] = a[i]; - a[i] = -2; // -2 = freed up + a[j] = x; + x = -2; // -2 = freed up } long long checksum = 0; diff --git a/2024/09/day09b.cpp b/2024/09/day09b.cpp index 3b1ac21..c304ed4 100644 --- a/2024/09/day09b.cpp +++ b/2024/09/day09b.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -21,16 +22,16 @@ int main() { a.push_back(id % 2 == 0 ? id/2 : -1); // -1 = space } - for (int i = file.size()-1; i >= 0; i--) { + for (auto& p : file | views::reverse) { 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; + if (f.first >= p.first) break; + if (f.second >= p.second) { + for (int k = 0; k < p.second; k++) { + a[f.first+k] = a[p.first+k]; + a[p.first+k] = -2; } - f.first += file[i].second; - f.second -= file[i].second; + f.first += p.second; + f.second -= p.second; break; } } diff --git a/2024/learned.txt b/2024/learned.txt index 86d32ff..56fa515 100644 --- a/2024/learned.txt +++ b/2024/learned.txt @@ -7,3 +7,4 @@ List of things I learned (or refreshed) with this year's AoC. to assign two variables at once with a pair of references pair * Day 5: std::find and std::replace * Day 8: set::insert_range(), but it is from C++23 only +* Day 9: std::views diff --git a/2024/template.cpp b/2024/template.cpp index b2fd4ec..2475ae7 100644 --- a/2024/template.cpp +++ b/2024/template.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include -- cgit v1.3