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