diff options
Diffstat (limited to '2024/src')
| -rw-r--r-- | 2024/src/day03.cpp | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/2024/src/day03.cpp b/2024/src/day03.cpp new file mode 100644 index 0000000..5b6ec9e --- /dev/null +++ b/2024/src/day03.cpp | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | #include <fstream> | ||
| 2 | #include <iostream> | ||
| 3 | #include <iterator> | ||
| 4 | #include <regex> | ||
| 5 | #include <string> | ||
| 6 | using namespace std; | ||
| 7 | |||
| 8 | string | ||
| 9 | read_file(string_view filename) | ||
| 10 | { | ||
| 11 | fstream input{ filename }; | ||
| 12 | return { istream_iterator<char>{ input }, {} }; | ||
| 13 | } | ||
| 14 | |||
| 15 | void | ||
| 16 | part1(const string& data) | ||
| 17 | { | ||
| 18 | static const regex pattern(R"(mul\(\d{1,3},\d{1,3}\))"); | ||
| 19 | |||
| 20 | long sum = 0; | ||
| 21 | for ( auto it = sregex_iterator(data.begin(), data.end(), pattern); it != sregex_iterator(); ++it ) { | ||
| 22 | long lhs = 0; | ||
| 23 | long rhs = 0; | ||
| 24 | sscanf(it->str().c_str(), "mul(%ld,%ld)", &lhs, &rhs); | ||
| 25 | sum += lhs * rhs; | ||
| 26 | } | ||
| 27 | cout << sum << endl; | ||
| 28 | } | ||
| 29 | |||
| 30 | void | ||
| 31 | part2(const string& data) | ||
| 32 | { | ||
| 33 | static const regex pattern(R"(do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))"); | ||
| 34 | |||
| 35 | long sum = 0; | ||
| 36 | bool state = true; | ||
| 37 | for ( auto it = sregex_iterator(data.begin(), data.end(), pattern); it != sregex_iterator(); ++it ) { | ||
| 38 | if ( it->str() == "do()" ) { | ||
| 39 | state = true; | ||
| 40 | } | ||
| 41 | else if ( it->str() == "don't()" ) { | ||
| 42 | state = false; | ||
| 43 | } | ||
| 44 | else if ( state ) { | ||
| 45 | long lhs = 0; | ||
| 46 | long rhs = 0; | ||
| 47 | sscanf(it->str().c_str(), "mul(%ld,%ld)", &lhs, &rhs); | ||
| 48 | sum += lhs * rhs; | ||
| 49 | } | ||
| 50 | } | ||
| 51 | cout << sum << endl; | ||
| 52 | } | ||
| 53 | |||
| 54 | int | ||
| 55 | main() | ||
| 56 | { | ||
| 57 | auto data = read_file("data/day03.txt"); | ||
| 58 | part1(data); | ||
| 59 | part2(data); | ||
| 60 | } | ||
