-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.cpp
101 lines (84 loc) · 2.37 KB
/
day2.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <bits/stdc++.h>
using namespace std;
bool isSafe(const vector<int>& report) {
bool isIncreasing = false;
bool isDecreasing = false;
for (int i = 1; i < report.size(); i++) {
int diff = report[i] - report[i - 1];
if (diff == 0 || abs(diff) > 3) {
isIncreasing = false;
isDecreasing = false;
break;
}
// Check direction
if (diff > 0) {
isIncreasing = true;
} else if (diff < 0) {
isDecreasing = true;
}
}
// A report is safe if it is exclusively increasing or decreasing
if (isIncreasing != isDecreasing) {
return true;
}
return false;
}
int main() {
// Get input
vector<vector<int>> reports;
string line;
while (getline(cin, line) && !line.empty()) {
stringstream ss(line);
vector<int> report;
int x;
while (ss >> x) {
report.push_back(x);
}
reports.push_back(report);
}
// Part 1
int numSafe = 0;
for (const vector<int>& report : reports) {
bool isIncreasing = false;
bool isDecreasing = false;
for (int i = 1; i < report.size(); i++) {
int diff = report[i] - report[i - 1];
if (diff == 0 || abs(diff) > 3) {
isIncreasing = false;
isDecreasing = false;
break;
}
// Check direction
if (diff > 0) {
isIncreasing = true;
} else if (diff < 0) {
isDecreasing = true;
}
}
// A report is safe if it is strictly increasing or strictly decreasing
if (isIncreasing != isDecreasing) {
numSafe++;
}
}
cout << numSafe << endl;
// Part 2
numSafe = 0;
bool usedDampener;
for (const vector<int>& report : reports) {
usedDampener = false;
if (isSafe(report)) {
numSafe++;
} else {
// Try removing each number and see if it's safe
for (int i=0;i<report.size();i++) {
vector<int> reportClone = report;
reportClone.erase(reportClone.begin() + i);
if (isSafe(reportClone)) {
numSafe++;
break;
}
}
}
}
cout << numSafe << endl;
}