78 lines
1.7 KiB
C++
78 lines
1.7 KiB
C++
|
#include <fstream>
|
||
|
#include <iostream>
|
||
|
#include <string>
|
||
|
#include <vector>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
|
||
|
vector<int> parse_line(string line) {
|
||
|
int start = 0;
|
||
|
vector<int> result;
|
||
|
while (start < line.length()) {
|
||
|
int end = line.find(" ", start);
|
||
|
|
||
|
string word = line.substr(start, end - start);
|
||
|
int n = stoi(word);
|
||
|
result.push_back(n);
|
||
|
|
||
|
start = end + 1;
|
||
|
if (end == -1) {
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return result;
|
||
|
}
|
||
|
|
||
|
|
||
|
bool is_valid(vector<int> report) {
|
||
|
int prev_diff = 0;
|
||
|
for (int i = 1; i < report.size(); i++) {
|
||
|
int diff = report[i] - report[i - 1];
|
||
|
if (diff < -3 || diff == 0 || diff > 3) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
// on the first iteration, we can't compare to the previous difference
|
||
|
if (i == 1) {
|
||
|
prev_diff = diff;
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
if ((diff > 0 && prev_diff < 0) || (diff < 0 && prev_diff > 0)) {
|
||
|
return false;
|
||
|
}
|
||
|
prev_diff = diff;
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
|
||
|
int main() {
|
||
|
ifstream file("data/02.txt");
|
||
|
string line;
|
||
|
int count_part1 = 0;
|
||
|
int count_part2 = 0;
|
||
|
while (getline(file, line)) {
|
||
|
auto report = parse_line(line);
|
||
|
if (is_valid(report)) {
|
||
|
count_part1++;
|
||
|
count_part2++;
|
||
|
}
|
||
|
else {
|
||
|
for (int i = 0; i < report.size(); i++) {
|
||
|
int n = report[i];
|
||
|
report.erase(report.begin() + i);
|
||
|
if (is_valid(report)) {
|
||
|
count_part2++;
|
||
|
break;
|
||
|
}
|
||
|
report.insert(report.begin() + i, n);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
cout << "Part 1: " << count_part1 << "\n";
|
||
|
cout << "Part 2: " << count_part2 << "\n";
|
||
|
}
|