main.cpp (1601B)
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 <regex> 10 11 std::string read_file(const std::string &path) { 12 std::ifstream ifs(path, std::ios::binary); 13 if (!ifs.is_open()) { 14 throw std::runtime_error(path+":"+std::strerror(errno)); 15 } 16 std::uintmax_t size = std::filesystem::file_size(path); 17 std::vector<char> buf(size); 18 if (!ifs.read((char *)buf.data(), buf.size())) { 19 throw std::runtime_error(path+":"+std::strerror(errno)); 20 } 21 return std::string(buf.data(), size); 22 } 23 24 int part1(std::string input) { 25 std::regex expr("mul\\((\\d+),(\\d+)\\)"); 26 auto r_begin = std::sregex_iterator(input.begin(), input.end(), expr); 27 auto r_end = std::sregex_iterator(); 28 int sum = 0; 29 for (auto i=r_begin; i!=r_end; ++i) { 30 int a = std::atoi((*i)[1].str().c_str()); 31 int b = std::atoi((*i)[2].str().c_str()); 32 sum += a*b; 33 } 34 return sum; 35 } 36 37 int part2(std::string input) { 38 std::regex expr("don't\\(\\).*?(do\\(\\)|$)"); 39 std::string noeol = std::regex_replace(input, std::regex("\n"), ""); 40 std::string cleaned = std::regex_replace(noeol, expr, ""); 41 return part1(cleaned); 42 } 43 44 int main(int argc, char **argv) { 45 const std::string fname = argc>1 ? argv[1] : "test1.txt"; 46 std::cout << "AoC 2024 day 03 " << fname << std::endl; 47 std::string input = read_file(fname); 48 std::cout << "part1: " << part1(input) << std::endl; 49 std::cout << "part2: " << part2(input) << std::endl; 50 51 return 0; 52 }