#include #include #include #include std::string readTextFromFile(const std::string& fileName) { std::vector lines; std::ifstream file(fileName); if (!file) { // Überprüft, ob die Datei geöffnet werden konnte std::cerr << "Fehler: Datei konnte nicht geöffnet werden: " << fileName << std::endl; return ""; } std::string result; std::string s; while(getline(file, s)) { result += s; } return result; } int checkForSubstringBefore(std::string& content, const std::string substring, size_t startPosition) { size_t pos = 0; int previousOccurence = -1; while ((pos = content.find(substring, pos)) != std::string::npos) { if(pos > startPosition) { return previousOccurence; } else { previousOccurence = pos; } pos += substring.length(); } return previousOccurence; } std::vector determineValidMuls(std::string& content, bool checkEnabled=false) { std::vector validMuls; std::regex regex(R"(mul\(\d{1,3},\d{1,3}\))"); auto begin = std::sregex_iterator(content.begin(), content.end(), regex); auto end = std::sregex_iterator(); for(auto it = begin; it != end; ++it) { if(checkEnabled) { int dont_start = checkForSubstringBefore(content, "don't()", it->position()); int do_start = checkForSubstringBefore(content, "do()", it->position()); if(dont_start < 0) { validMuls.push_back(it->str()); } else if(do_start > dont_start) { validMuls.push_back(it->str()); } } else { validMuls.push_back(it->str()); } } return validMuls; } int calcMultOfMultOp(const std::string& multOp) { std::regex regex("\\d{1,3}"); auto begin = std::sregex_iterator(multOp.begin(), multOp.end(), regex); auto end = std::sregex_iterator(); int multResult = 1; for(auto it = begin; it != end; ++it) { multResult *= std::stoi(it->str()); } return multResult; } int calcMultSum(std::vector& validMuls) { int sum = 0; for(const auto& mul : validMuls) { sum += calcMultOfMultOp(mul); } return sum; } int main() { std::string content = readTextFromFile("../input.txt"); std::vector validMuls = determineValidMuls(content, false); int result = calcMultSum(validMuls); std::cout << "The correct Mult Result is: " << result << std::endl; std::vector validMulsWithChecks = determineValidMuls(content, true); int resultWithChecks = calcMultSum(validMulsWithChecks); std::cout << "The correct Mult Result with check is: " << resultWithChecks << std::endl; return 0; }