-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdayThreePartTwo.cpp
More file actions
98 lines (83 loc) · 2.49 KB
/
dayThreePartTwo.cpp
File metadata and controls
98 lines (83 loc) · 2.49 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
namespace DayThreePartTwo
{
namespace {
using std::string;
const bool toLog = true;
long handleLine(std::string line) { // operates on the read value, destructive function
const std::regex kMulPattern(R"(mul\((\d{1,3}),(\d{1,3})\))");
const int kMaxMulPatternLen = 12;
const std::regex kDoPattern(R"(do\(\))");
const std::regex kDontPattern(R"(don't\(\))");
const int kLongestDPatternLen = 7;
bool isMulEnabled = true;
long total = 0;
size_t pos = 0;
while (pos < line.size()) {
size_t mPos = line.find('m', pos);
size_t dPos = line.find('d', pos);
size_t nextPos = std::min(mPos, dPos);
if (nextPos == std::string::npos) break;
char foundChar = line[nextPos];
switch (foundChar) {
case 'm': {
if (!isMulEnabled) break;
std::string subLine = line.substr(nextPos, kMaxMulPatternLen);
std::smatch match;
if (std::regex_search(subLine, match, kMulPattern)) {
if (toLog) std::cout << match[0].str();
if (match.position(0) == 0) {
int num1 = std::stol(match[1].str());
int num2 = std::stol(match[2].str());
total += num1 * num2;
if (toLog) std::cout << ";" << total << ';';
}
else std::cout << "!!!!!!!!!!";
}
break;
}
case 'd': {
std::string subLine = line.substr(nextPos, kLongestDPatternLen);
std::smatch match;
if (std::regex_search(subLine, match, kDoPattern) && match.position(0) == 0) {
if (toLog) std::cout << "DO[]";
isMulEnabled = true;
}
else if (std::regex_search(subLine, match, kDontPattern) && match.position(0) == 0) {
if (toLog) std::cout << "DON'T[]";
isMulEnabled = false;
}
break;
}
}
pos = nextPos + 1;
}
std::cout << '\n' << "total: " << total << '\n';
return total;
}
}
void dayThreePartTwo() {
std::cout << "Running program dayThree Part Two" << '\n';
std::string line;
std::ifstream inputFile("dayThreeFull.txt");
long totalAllLines = 0;
if (inputFile.is_open())
{
while (getline(inputFile, line)) {
if (toLog) std::cout << '\n' << line << "\n\n";
totalAllLines += handleLine(line);
}
std::cout << "Total: " << totalAllLines << '\n';
std::cout << "Finished reading file\n";
}
else std::cout << "Unable to open file\n";
}
}
// 79037122 too high
// 75532820 too low
// Solution: remove newlines and treat the dataset as a full line
// dayThreeTest
// dayThreeFull