diff --git a/q1.cpp b/q1.cpp index 36401ec..ffa6f7f 100644 --- a/q1.cpp +++ b/q1.cpp @@ -1,66 +1,57 @@ #include #include #include +#include #include #include #include int q1(std::ifstream &in) { - std::vector l1; - std::vector 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)); - // } + std::vector l1; + std::vector l2; - for (std::string line; std::getline(in, line);) { - int left, right; - std::stringstream s(line); - s >> left >> right; - l1.push_back(left); - l2.push_back(right); - } + for (std::string line; std::getline(in, line);) { + int left, right; + std::stringstream(line) >> left >> right; - std::sort(l1.begin(), l1.end()); - std::sort(l2.begin(), l2.end()); + l1.push_back(left); + l2.push_back(right); + } - int sum = 0; - for (int i = 0; i < l1.size(); i++) { - sum += abs(l1[i]-l2[i]); - } - return sum; + 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; } int q2(std::ifstream &in) { - std::vector l1; - std::unordered_map 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::vector l1; + std::unordered_map l2; - 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; - for (int i = 0; i < l1.size(); i++) { - sum += l1[i] * l2[l1[i]]; - } - return sum; + l1.push_back(left); + l2[right]++; + } + + return std::accumulate(l1.begin(), l1.end(), 0, [&l2](int acc, int curr) { + return acc + curr * l2[curr]; + }); } int main() { - std::ifstream input("i1.txt"); - std::cout << "Part 1: " << q1(input) << std::endl; + 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; + // 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; }