Fixed issue where newlines in the data would reset the multiplying flag.

This commit is contained in:
David Vereb 2024-12-04 10:54:49 -05:00
parent 2317ec628a
commit c4d14c613d
2 changed files with 18 additions and 25 deletions

View File

@ -1,2 +1,2 @@
a.out: main.cpp a.out: main.cpp
clang++ -std=c++2b -g -O0 main.cpp clang++ -std=c++2b -g -O0 main.cpp #-fsanitize=address -fno-omit-frame-pointer

View File

@ -18,36 +18,24 @@ int main()
unsigned long total = 0; unsigned long total = 0;
unsigned long total_pt2 = 0; unsigned long total_pt2 = 0;
long dos = 0; bool multiplying = true;
long donts = 0;
for(std::string line; std::getline(ifs, line); ) for(std::string line; std::getline(ifs, line); )
{ {
if(line == "") if(line == "")
continue; continue;
std::regex pattern("do\\(\\)|don\\'t\\(\\)|mul\\((\\d+),(\\d+)\\)"); std::regex pattern("do\\(\\)|don't\\(\\)|mul\\((\\d+),(\\d+)\\)");
auto pattern_begin = std::sregex_iterator(line.begin(), line.end(), pattern); auto pattern_begin = std::sregex_iterator(line.begin(), line.end(), pattern);
auto pattern_end = std::sregex_iterator(); auto pattern_end = std::sregex_iterator();
bool multiplying = true;
for (std::sregex_iterator i = pattern_begin; i != pattern_end; ++i) for (std::sregex_iterator i = pattern_begin; i != pattern_end; ++i)
{ {
std::string result = i->str(); std::string result = i->str();
std::cout << result << std::endl;
if(i->str() == "do()") if(i->str() == "do()")
{
++dos;
std::cout << "\033[0m";
multiplying = true; multiplying = true;
}
else if(i->str() == "don't()") else if(i->str() == "don't()")
{
++donts;
std::cout << "\033[1;31m";
multiplying = false; multiplying = false;
}
else else
{ {
std::smatch::iterator ip_it = i->begin(); std::smatch::iterator ip_it = i->begin();
@ -57,16 +45,24 @@ int main()
advance(ip_it, 1)) advance(ip_it, 1))
{ {
std::string n = *ip_it; std::string n = *ip_it;
numbers.push_back(std::atoi(n.c_str())); try {
numbers.push_back(std::atoi(n.c_str()));
} catch(const std::exception &e) {
std::cout << "ERROR: " << e.what() << std::endl;
exit(-1);
}
} }
long result = 1; long result = 1;
for(auto n : numbers) if(numbers.size())
result *= n; {
std::cout << result << std::endl; for(auto n : numbers)
if(multiplying) result *= n;
total_pt2 += result;
total += result; if(multiplying)
total_pt2 += result;
total += result;
}
} }
} }
} }
@ -74,8 +70,5 @@ int main()
std::cout << " Total: " << total << std::endl; std::cout << " Total: " << total << std::endl;
std::cout << "PT2 Total: " << total_pt2 << std::endl; std::cout << "PT2 Total: " << total_pt2 << std::endl;
std::cout << "do()s: " << dos << std::endl;
std::cout << "don't()s: " << donts << std::endl;
return 0; return 0;
} }