68 lines
1.8 KiB
C++
68 lines
1.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;
|
|
}
|
|
|
|
std::vector<std::string> determineValidMuls(std::string& content) {
|
|
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) {
|
|
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::cout << content << std::endl;
|
|
|
|
std::vector<std::string> validMuls = determineValidMuls(content);
|
|
for(const auto& mul : validMuls) {
|
|
std::cout << mul << std::endl;
|
|
}
|
|
|
|
int result = calcMultSum(validMuls);
|
|
std::cout << "The correct Mult Result is: " << result << std::endl;
|
|
return 0;
|
|
}
|