94 lines
2.8 KiB
C++
94 lines
2.8 KiB
C++
#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;
|
|
}
|
|
|
|
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}\))");
|
|
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<std::string>& validMuls) {
|
|
int sum = 0;
|
|
for(const auto& mul : validMuls) {
|
|
sum += calcMultOfMultOp(mul);
|
|
}
|
|
return sum;
|
|
}
|
|
|
|
int main() {
|
|
std::string content = readTextFromFile("../input.txt");
|
|
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;
|
|
}
|