Try to use more idiomatic C++

This commit is contained in:
Kiril Kovachev 2024-12-01 06:10:04 +00:00
parent d9bdd40d0a
commit e2c1c14b3d

81
q1.cpp
View File

@ -1,66 +1,57 @@
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <numeric>
#include <sstream> #include <sstream>
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
int q1(std::ifstream &in) { int q1(std::ifstream &in) {
std::vector<int> l1; std::vector<int> l1;
std::vector<int> l2; std::vector<int> l2;
// for (std::string line; std::getline(in, line);) {
// std::string left = line.substr(0, line.find(" "));
// std::string right = line.substr(line.rfind(" "));
// l1.push_back(std::stoi(left));
// l2.push_back(std::stoi(right));
// }
for (std::string line; std::getline(in, line);) { for (std::string line; std::getline(in, line);) {
int left, right; int left, right;
std::stringstream s(line); std::stringstream(line) >> left >> right;
s >> left >> right;
l1.push_back(left);
l2.push_back(right);
}
std::sort(l1.begin(), l1.end()); l1.push_back(left);
std::sort(l2.begin(), l2.end()); l2.push_back(right);
}
int sum = 0; std::sort(l1.begin(), l1.end());
for (int i = 0; i < l1.size(); i++) { std::sort(l2.begin(), l2.end());
sum += abs(l1[i]-l2[i]);
} int sum = 0;
return sum; for (int i = 0; i < l1.size(); i++) {
sum += abs(l1[i] - l2[i]);
}
return sum;
} }
int q2(std::ifstream &in) { int q2(std::ifstream &in) {
std::vector<int> l1; std::vector<int> l1;
std::unordered_map<int, int> l2; std::unordered_map<int, int> l2;
for (std::string line; std::getline(in, line);) {
std::string left = line.substr(0, line.find(" "));
std::string right = line.substr(line.rfind(" "));
l1.push_back(std::stoi(left));
l2[std::stoi(right)]++;
}
std::sort(l1.begin(), l1.end()); for (std::string line; std::getline(in, line);) {
int left, right;
std::stringstream(line) >> left >> right;
int sum = 0; l1.push_back(left);
for (int i = 0; i < l1.size(); i++) { l2[right]++;
sum += l1[i] * l2[l1[i]]; }
}
return sum; return std::accumulate(l1.begin(), l1.end(), 0, [&l2](int acc, int curr) {
return acc + curr * l2[curr];
});
} }
int main() { int main() {
std::ifstream input("i1.txt"); std::ifstream input("i1.txt");
std::cout << "Part 1: " << q1(input) << std::endl; std::cout << "Part 1: " << q1(input) << std::endl;
// Could re-read the file, or just seek to the beginning. // Could re-read the file, or just seek to the beginning.
// input = std::ifstream("i1.txt"); // input = std::ifstream("i1.txt");
input.clear(); input.clear();
input.seekg(0); input.seekg(0);
std::cout << "Part 2: " << q2(input) << std::endl; std::cout << "Part 2: " << q2(input) << std::endl;
} }