AdventOfCode2024/Aufgabe 3/main.cpp

94 lines
2.8 KiB
C++
Raw Permalink Normal View History

2024-12-08 09:31:44 +00:00
#include <iostream>
#include <vector>
#include <fstream>
#include <regex>
std::string readTextFromFile(const std::string& fileName) {
std::vector<std::string> 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;
}
2024-12-08 10:06:34 +00:00
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) {
2024-12-08 09:31:44 +00:00
std::vector<std::string> 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) {
2024-12-08 10:06:34 +00:00
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());
}
2024-12-08 09:31:44 +00:00
}
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<std::string>& validMuls) {
int sum = 0;
for(const auto& mul : validMuls) {
sum += calcMultOfMultOp(mul);
}
return sum;
}
int main() {
std::string content = readTextFromFile("../input.txt");
2024-12-08 10:06:34 +00:00
std::vector<std::string> validMuls = determineValidMuls(content, false);
2024-12-08 09:31:44 +00:00
int result = calcMultSum(validMuls);
std::cout << "The correct Mult Result is: " << result << std::endl;
2024-12-08 10:06:34 +00:00
std::vector<std::string> validMulsWithChecks = determineValidMuls(content, true);
int resultWithChecks = calcMultSum(validMulsWithChecks);
std::cout << "The correct Mult Result with check is: " << resultWithChecks << std::endl;
2024-12-08 09:31:44 +00:00
return 0;
}