diff --git a/2024/02.cpp b/2024/02.cpp new file mode 100644 index 0000000..5267383 --- /dev/null +++ b/2024/02.cpp @@ -0,0 +1,77 @@ +#include +#include +#include +#include + +using namespace std; + + +vector parse_line(string line) { + int start = 0; + vector 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 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"; +}