98 lines
2.1 KiB
C++
98 lines
2.1 KiB
C++
#include <fstream>
|
|
#include <iostream>
|
|
using namespace std;
|
|
|
|
// parses a number with up to 3 digits
|
|
bool parseNumber(ifstream &input, int &x, char delim) {
|
|
char c1;
|
|
char c2;
|
|
char c3;
|
|
|
|
input >> c1;
|
|
if (c1 < '0' || c1 > '9') return false;
|
|
|
|
x = c1 - 48;
|
|
if (input.peek() == delim) return true;
|
|
|
|
input >> c2;
|
|
if (c2 < '0' || c2 > '9') return false;
|
|
x *= 10;
|
|
x += c2 - 48;
|
|
|
|
if (input.peek() == delim) return true;
|
|
|
|
input >> c3;
|
|
if (c3 < '0' || c3 > '9') return false;
|
|
x *= 10;
|
|
x += c3 - 48;
|
|
|
|
return true;
|
|
}
|
|
|
|
bool peekCheck (ifstream &input, char c) {
|
|
char x;
|
|
if (input.peek() == c) {
|
|
input >> x;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
int day3(const char *path, bool extra = true) {
|
|
ifstream input(path);
|
|
int result = 0;
|
|
char c;
|
|
bool enable = true;
|
|
|
|
while (input >> c) {
|
|
if (extra) {
|
|
if (c == 'd') {
|
|
if (!peekCheck(input, 'o')) continue;
|
|
|
|
if (peekCheck(input, '(') && peekCheck(input, ')')) {
|
|
enable = true;
|
|
continue;
|
|
}
|
|
|
|
if (!peekCheck(input, 'n')) continue;
|
|
if (!peekCheck(input, '\'')) continue;
|
|
if (!peekCheck(input, 't')) continue;
|
|
if (!peekCheck(input, '(')) continue;
|
|
if (!peekCheck(input, ')')) continue;
|
|
|
|
enable = false;
|
|
}
|
|
}
|
|
if (c == 'm') {
|
|
if (!peekCheck(input, 'u')) continue;
|
|
if (!peekCheck(input, 'l')) continue;
|
|
if (!peekCheck(input, '(')) continue;
|
|
|
|
int x;
|
|
parseNumber(input, x, ',');
|
|
|
|
if (!peekCheck(input, ',')) continue;
|
|
|
|
int y;
|
|
parseNumber(input, y, ')');
|
|
|
|
if (!peekCheck(input, ')')) continue;
|
|
|
|
if (enable) result += x * y;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
int result = day3("example", false);
|
|
cout << "example (without do)" << endl << result << endl;
|
|
result = day3("example", true);
|
|
cout << "example (with do)" << endl << result << endl;
|
|
result = day3("input", false);
|
|
cout << "input (without do)" << endl << result << endl;
|
|
result = day3("input", true);
|
|
cout << "input (without do)" << endl << result << endl;
|
|
|
|
return 0;
|
|
}
|