Skip to content

Commit

Permalink
reusing checksum
Browse files Browse the repository at this point in the history
  • Loading branch information
K20shores committed Dec 9, 2024
1 parent 5c5eb13 commit a01d064
Showing 1 changed file with 20 additions and 33 deletions.
53 changes: 20 additions & 33 deletions 2024/src/day9.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ void print(auto list) {
formatted(list);
}

long long checksum(std::list<std::pair<int, int>> diskmap) {
long long sum = 0;
auto left = diskmap.begin();
int i = 0;
while(left != diskmap.end()) {
if (left->first != -1) {
for(int j = 0; j < left->second; ++j, ++i) {
sum += left->first * i;
}
}
else {
i += left->second;
}
++left;
}
return sum;
}

long long part1(const Data &data)
{
auto diskmap = data.diskmap;
Expand Down Expand Up @@ -75,22 +93,7 @@ long long part1(const Data &data)
}

// print(diskmap);

long long sum = 0;
left = diskmap.begin();
int i = 0;
while(left != diskmap.end()) {
if (left->first != -1) {
for(int j = 0; j < left->second; ++j, ++i) {
sum += left->first * i;
}
}
else {
i += left->second;
}
++left;
}
return sum;
return checksum(diskmap);
}

long long part2(const Data &data)
Expand Down Expand Up @@ -134,7 +137,6 @@ long long part2(const Data &data)
}
moved.insert(left->first);
left = diskmap.begin();

// the block at the end is now unallocated
right->first = -1;
}
Expand All @@ -145,22 +147,7 @@ long long part2(const Data &data)
}

// print(diskmap);

long long sum = 0;
left = diskmap.begin();
int i = 0;
while(left != diskmap.end()) {
if (left->first != -1) {
for(int j = 0; j < left->second; ++j, ++i) {
sum += left->first * i;
}
}
else {
i += left->second;
}
++left;
}
return sum;
return checksum(diskmap);
}

Data parse()
Expand Down

0 comments on commit a01d064

Please sign in to comment.