Advent-Of-Code-2024/q1.cpp

58 lines
1.2 KiB
C++
Raw Permalink Normal View History

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