#include #include #include #include #include #include int main() { const std::string filename = "data.txt"; std::ifstream ifs(filename); if(!ifs.is_open()) { std::cerr << "Missing " << filename << "." << std::endl; return -1; } unsigned long total = 0; unsigned long total_pt2 = 0; bool multiplying = true; for(std::string line; std::getline(ifs, line); ) { if(line == "") continue; std::regex pattern("do\\(\\)|don't\\(\\)|mul\\((\\d+),(\\d+)\\)"); auto pattern_begin = std::sregex_iterator(line.begin(), line.end(), pattern); auto pattern_end = std::sregex_iterator(); for (std::sregex_iterator i = pattern_begin; i != pattern_end; ++i) { std::string result = i->str(); if(i->str() == "do()") multiplying = true; else if(i->str() == "don't()") multiplying = false; else { std::smatch::iterator ip_it = i->begin(); std::vector numbers; for (std::advance(ip_it, 1); ip_it != i->end(); advance(ip_it, 1)) { std::string n = *ip_it; try { numbers.push_back(std::atoi(n.c_str())); } catch(const std::exception &e) { std::cout << "ERROR: " << e.what() << std::endl; exit(-1); } } long result = 1; if(numbers.size()) { for(auto n : numbers) result *= n; if(multiplying) total_pt2 += result; total += result; } } } } std::cout << " Total: " << total << std::endl; std::cout << "PT2 Total: " << total_pt2 << std::endl; return 0; }