diff --git a/Aufgabe 3/input_example.txt b/Aufgabe 3/input_example.txt index 2e1a90a..b774ec9 100644 --- a/Aufgabe 3/input_example.txt +++ b/Aufgabe 3/input_example.txt @@ -1 +1 @@ -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) \ No newline at end of file +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) \ No newline at end of file diff --git a/Aufgabe 3/main.cpp b/Aufgabe 3/main.cpp index 6a42d33..f9d2830 100644 --- a/Aufgabe 3/main.cpp +++ b/Aufgabe 3/main.cpp @@ -18,7 +18,21 @@ std::string readTextFromFile(const std::string& fileName) { return result; } -std::vector determineValidMuls(std::string& content) { +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}\))"); @@ -26,7 +40,19 @@ std::vector determineValidMuls(std::string& content) { auto end = std::sregex_iterator(); for(auto it = begin; it != end; ++it) { - validMuls.push_back(it->str()); + 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; } @@ -54,14 +80,14 @@ int calcMultSum(std::vector& validMuls) { int main() { std::string content = readTextFromFile("../input.txt"); - std::cout << content << std::endl; - - std::vector validMuls = determineValidMuls(content); - for(const auto& mul : validMuls) { - std::cout << mul << std::endl; - } + 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; }