aboutsummaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-12-03 18:09:36 +0100
committerThomas Schmucker <ts@its1.de>2024-12-03 18:09:36 +0100
commit6bdb9bc94c54b9ae37d7a358057d84c893428e0b (patch)
tree0453f0e70d6b69ea751f7f4ead85a55e92e30112 /2024
parentc7df2c89969cc78f0e86b090eef64e2cce4e3325 (diff)
downloadadvent-of-code-6bdb9bc94c54b9ae37d7a358057d84c893428e0b.tar.gz
advent-of-code-6bdb9bc94c54b9ae37d7a358057d84c893428e0b.tar.bz2
advent-of-code-6bdb9bc94c54b9ae37d7a358057d84c893428e0b.zip
benutze sub-groups in der regex; kein sscanf() mehr
Diffstat (limited to '2024')
-rw-r--r--2024/src/day03.cpp18
1 files changed, 6 insertions, 12 deletions
diff --git a/2024/src/day03.cpp b/2024/src/day03.cpp
index 5b6ec9e..bfbd781 100644
--- a/2024/src/day03.cpp
+++ b/2024/src/day03.cpp
@@ -15,14 +15,11 @@ read_file(string_view filename)
15void 15void
16part1(const string& data) 16part1(const string& data)
17{ 17{
18 static const regex pattern(R"(mul\(\d{1,3},\d{1,3}\))"); 18 static const regex pattern{ R"(mul\((\d{1,3}),(\d{1,3})\))" };
19 19
20 long sum = 0; 20 long sum = 0;
21 for ( auto it = sregex_iterator(data.begin(), data.end(), pattern); it != sregex_iterator(); ++it ) { 21 for ( auto it = sregex_iterator{ data.begin(), data.end(), pattern }; it != sregex_iterator{}; ++it ) {
22 long lhs = 0; 22 sum += stol((*it)[1]) * stol((*it)[2]);
23 long rhs = 0;
24 sscanf(it->str().c_str(), "mul(%ld,%ld)", &lhs, &rhs);
25 sum += lhs * rhs;
26 } 23 }
27 cout << sum << endl; 24 cout << sum << endl;
28} 25}
@@ -30,11 +27,11 @@ part1(const string& data)
30void 27void
31part2(const string& data) 28part2(const string& data)
32{ 29{
33 static const regex pattern(R"(do\(\)|don't\(\)|mul\(\d{1,3},\d{1,3}\))"); 30 static const regex pattern{ R"(do\(\)|don't\(\)|mul\((\d{1,3}),(\d{1,3})\))" };
34 31
35 long sum = 0; 32 long sum = 0;
36 bool state = true; 33 bool state = true;
37 for ( auto it = sregex_iterator(data.begin(), data.end(), pattern); it != sregex_iterator(); ++it ) { 34 for ( auto it = sregex_iterator{ data.begin(), data.end(), pattern }; it != sregex_iterator{}; ++it ) {
38 if ( it->str() == "do()" ) { 35 if ( it->str() == "do()" ) {
39 state = true; 36 state = true;
40 } 37 }
@@ -42,10 +39,7 @@ part2(const string& data)
42 state = false; 39 state = false;
43 } 40 }
44 else if ( state ) { 41 else if ( state ) {
45 long lhs = 0; 42 sum += stol((*it)[1]) * stol((*it)[2]);
46 long rhs = 0;
47 sscanf(it->str().c_str(), "mul(%ld,%ld)", &lhs, &rhs);
48 sum += lhs * rhs;
49 } 43 }
50 } 44 }
51 cout << sum << endl; 45 cout << sum << endl;