Day 3: Part 2

This commit is contained in:
Fawkes100 2024-12-08 11:06:34 +01:00
parent 216d18d56f
commit 840b283631
2 changed files with 35 additions and 9 deletions

View File

@ -1 +1 @@
xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))

View File

@ -18,7 +18,21 @@ std::string readTextFromFile(const std::string& fileName) {
return result;
}
std::vector<std::string> 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<std::string> determineValidMuls(std::string& content, bool checkEnabled=false) {
std::vector<std::string> validMuls;
std::regex regex(R"(mul\(\d{1,3},\d{1,3}\))");
@ -26,7 +40,19 @@ std::vector<std::string> determineValidMuls(std::string& content) {
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;
}
@ -54,14 +80,14 @@ int calcMultSum(std::vector<std::string>& validMuls) {
int main() {
std::string content = readTextFromFile("../input.txt");
std::cout << content << std::endl;
std::vector<std::string> validMuls = determineValidMuls(content);
for(const auto& mul : validMuls) {
std::cout << mul << std::endl;
}
std::vector<std::string> validMuls = determineValidMuls(content, false);
int result = calcMultSum(validMuls);
std::cout << "The correct Mult Result is: " << result << std::endl;
std::vector<std::string> validMulsWithChecks = determineValidMuls(content, true);
int resultWithChecks = calcMultSum(validMulsWithChecks);
std::cout << "The correct Mult Result with check is: " << resultWithChecks << std::endl;
return 0;
}