aboutsummaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
Diffstat (limited to '2024')
-rw-r--r--2024/src/day09.cpp88
1 files changed, 88 insertions, 0 deletions
diff --git a/2024/src/day09.cpp b/2024/src/day09.cpp
index dd25a9d..7787c5c 100644
--- a/2024/src/day09.cpp
+++ b/2024/src/day09.cpp
@@ -1,7 +1,10 @@
1#include <fstream> 1#include <fstream>
2#include <iostream> 2#include <iostream>
3#include <iterator> 3#include <iterator>
4#include <list>
5#include <ranges>
4#include <string> 6#include <string>
7#include <vector>
5using namespace std; 8using namespace std;
6 9
7vector<int> 10vector<int>
@@ -50,9 +53,94 @@ part1(const vector<int>& data)
50 cout << sum << endl; 53 cout << sum << endl;
51} 54}
52 55
56void
57part2(const vector<int>& data)
58{
59 // id, pos, len
60 vector<tuple<int, size_t, size_t>> files;
61
62 // pos, len
63 list<tuple<size_t, size_t>> spaces;
64
65 for ( size_t i = 0; i != data.size(); ) {
66 // skip space
67 auto j = i;
68 while ( j != data.size() && data.at(j) == -1 ) {
69 ++j;
70 }
71 if ( i != j ) {
72 spaces.emplace_back(i, j - i);
73 }
74 i = j;
75
76 while ( j != data.size() && data.at(i) == data.at(j) ) {
77 ++j;
78 }
79 if ( i != j ) {
80 files.emplace_back(data.at(i), i, j - i);
81 }
82 i = j;
83 }
84
85 for ( auto& file: std::ranges::reverse_view(files) ) {
86 for ( auto it = spaces.begin(); it != spaces.end(); ++it ) {
87 if ( get<0>(*it) >= get<1>(file) ) {
88 spaces.erase(it, spaces.end());
89 break;
90 }
91 if ( get<1>(*it) >= get<2>(file) ) {
92 // update pos
93 get<1>(file) = get<0>(*it);
94
95 // update space len
96 get<1>(*it) -= get<2>(file);
97
98 // update space pos
99 get<0>(*it) += get<2>(file);
100
101 if ( get<1>(*it) == 0 ) {
102 spaces.erase(it);
103 }
104 break;
105 }
106 }
107 }
108
109 /*
110 for ( auto& file: std::ranges::reverse_view(files) ) {
111 auto space = ranges::find_if(spaces, [&](const auto& space) -> bool {
112 return get<1>(space) >= get<2>(file) && get<0>(space) < get<1>(file);
113 });
114 if ( space != spaces.end() ) {
115 // update pos
116 get<1>(file) = get<0>(*space);
117
118 // update space len
119 get<1>(*space) -= get<2>(file);
120
121 // update space pos
122 get<0>(*space) += get<2>(file);
123
124 if ( get<1>(*space) == 0 ) {
125 spaces.erase(space);
126 }
127 }
128 }
129 */
130
131 long sum = 0;
132 for ( const auto& [fid, pos, size]: files ) {
133 for ( size_t x = pos; x != pos + size; ++x ) {
134 sum += long(x) * fid;
135 }
136 }
137 cout << sum << endl;
138}
139
53int 140int
54main() 141main()
55{ 142{
56 auto data = read_file("data/day09.txt"); 143 auto data = read_file("data/day09.txt");
57 part1(data); 144 part1(data);
145 part2(data);
58} 146}