-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path08.cpp
84 lines (74 loc) · 2.07 KB
/
08.cpp
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
#include <chrono>
#include <iostream>
#include <regex>
#include <string>
#include <unordered_map>
using std::regex;
using std::regex_match;
using std::smatch;
using std::string;
using std::string_view;
using std::unordered_map;
int main() {
auto tstart = std::chrono::high_resolution_clock::now();
int pt1 = 0;
int pt2 = 0;
string input;
unordered_map<string, int> registers;
regex rx("^(\\w+) (\\w+) (-?\\d+) if (\\w+) ([!><=]+) (-?\\d+)$");
smatch matches;
while (std::getline(std::cin, input)) {
regex_match(input, matches, rx);
// first, parse and execute guard clause
const string &cr = matches[4];
const string &cop = matches[5];
const int cv = std::stoi(matches[6]);
bool guard = false;
if (cop == ">=") {
guard = registers[cr] >= cv;
} else if (cop == "<=") {
guard = registers[cr] <= cv;
} else if (cop == ">") {
guard = registers[cr] > cv;
} else if (cop == "<") {
guard = registers[cr] < cv;
} else if (cop == "==") {
guard = registers[cr] == cv;
} else if (cop == "!=") {
guard = registers[cr] != cv;
}
if (!guard) {
continue;
}
// only then, execute instruction
const string &op = matches[2];
const string &r = matches[1];
const int amount = std::stoi(matches[3]);
if (op == "inc") {
registers[r] += amount;
} else {
registers[r] -= amount;
}
// keep track of running max for part 2
if (registers[r] > pt2) {
pt2 = registers[r];
}
}
// find max final register value for part 1
for (const auto &[_, value] : registers) {
if (value > pt1) {
pt1 = value;
}
}
std::cout << "--- Day 8: I Heard You Like Registers ---\n";
std::cout << "Part 1: " << pt1 << "\n";
std::cout << "Part 2: " << pt2 << "\n";
auto tstop = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::microseconds>(tstop - tstart);
std::cout << "Time: " << (static_cast<double>(duration.count()) / 1000.0)
<< " ms"
<< "\n";
return EXIT_SUCCESS;
;
}