advent2024

Advent of Code 2024
git clone git://bsandro.tech/advent2024
Log | Files | Refs

main.cpp (1662B)


      1 #include <iostream>
      2 #include <filesystem>
      3 #include <fstream>
      4 #include <vector>
      5 #include <cstring>
      6 #include <cstdio>
      7 #include <cmath>
      8 #include <tuple>
      9 #include <algorithm>
     10 
     11 typedef std::pair<std::vector<int>, std::vector<int>> Data;
     12 
     13 template<typename T>
     14 T read_file(const std::string &path) {
     15     std::ifstream ifs(path, std::ios::binary);
     16     if (!ifs.is_open()) {
     17         throw std::runtime_error(path+":"+std::strerror(errno));
     18     }
     19     T buf = make_pair(std::vector<int>{}, std::vector<int>{});
     20     while (1) {
     21         std::string str;
     22         std::getline(ifs, str);
     23         int a, b;
     24         std::sscanf(str.c_str(), "%d %d", &a, &b);
     25         if (!str.empty()) {
     26             buf.first.push_back(a);
     27             buf.second.push_back(b);
     28         }
     29         if (!ifs) break;
     30     }
     31     return buf;
     32 }
     33 
     34 int part1(Data &orig) {
     35     Data input = orig;
     36     std::sort(input.first.begin(), input.first.end());
     37     std::sort(input.second.begin(), input.second.end());
     38     int sum = 0;
     39     for (int i=0; i<(int)input.first.size(); ++i) {
     40         sum += std::abs(input.first[i] - input.second[i]);
     41     }
     42     return sum;
     43 }
     44 int part2(Data &input) {
     45     int sum = 0;
     46     for (int i=0; i<(int)input.first.size(); ++i) {
     47         sum += input.first[i] * std::count(input.second.begin(), input.second.end(), input.first[i]);
     48     }
     49     return sum;
     50 }
     51 
     52 int main(int argc, char **argv) {
     53     const std::string fname = argc>1 ? argv[1] : "test1.txt";
     54     std::cout << "AoC 2024 day 01 " << fname << std::endl;
     55     Data input = read_file<Data>(fname);
     56     std::cout << "part1: " << part1(input) << std::endl;
     57     std::cout << "part2: " << part2(input) << std::endl;
     58 
     59     return 0;
     60 }