advent2024

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

main.cpp (2104B)


      1 #include <iostream>
      2 #include <filesystem>
      3 #include <fstream>
      4 #include <vector>
      5 #include <cstring>
      6 #include <cstdio>
      7 #include <tuple>
      8 #include <algorithm>
      9 #include "utils.hpp"
     10 
     11 typedef std::array<int, 5> Scheme;
     12 typedef std::pair<std::vector<Scheme>, std::vector<Scheme>> Data;
     13 
     14 Data 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     std::vector<Scheme> keys;
     20     std::vector<Scheme> locks;
     21     Scheme s{0}; // current schematics
     22     bool is_key = false; // keys have line 0 empty; locks are upside down.
     23     bool is_new = true; // resets on newline
     24     while (1) {
     25         std::string str;
     26         std::getline(ifs, str);
     27         if (str.empty()) {
     28             is_new = true;
     29             if (is_key) keys.push_back(s);
     30             else locks.push_back(s);
     31         } else {
     32             if (is_new) {
     33                 is_key = (str == ".....");
     34                 is_new = false;
     35                 s.fill(is_key?-1:0);
     36             } else {
     37                 for (int i=0;i<(int)str.size();++i) {
     38                     if (str[i]=='#') s[i]++;
     39                 }
     40             }
     41         }
     42         if (!ifs) break;
     43     }
     44     return std::make_pair(keys, locks);
     45 }
     46 
     47 int64_t part1(Data &input [[ maybe_unused ]]) {
     48     auto &[keys, locks] = input;
     49     int64_t res = 0;
     50     for (auto &l:locks) {
     51         for (auto &k:keys) {
     52             bool fits = true;
     53             for (int i=0;i<5;++i) {
     54                 if (l[i]+k[i]>5) {
     55                     fits = false;
     56                     break;
     57                 }
     58             }
     59             if (fits) res++;
     60         }
     61     }
     62     return res;
     63 }
     64 int64_t part2(Data &input [[ maybe_unused ]]) {
     65     return 0;
     66 }
     67 
     68 int main(int argc, char **argv) {
     69     Performance perf;
     70     const std::string fname = argc>1 ? argv[1] : "test1.txt";
     71     std::cout << "AoC 2024 day 25 " << fname << std::endl;
     72     Data input = read_file(fname);
     73     std::cout << "part1: " << part1(input) << std::endl;
     74     std::cout << "part2: " << part2(input) << std::endl;
     75 
     76     return 0;
     77 }