finish day 2
This commit is contained in:
parent
11e1ceaa9f
commit
dc814495a0
3 changed files with 1089 additions and 0 deletions
6
02/example
Normal file
6
02/example
Normal file
|
@ -0,0 +1,6 @@
|
|||
7 6 4 2 1
|
||||
1 2 7 8 9
|
||||
9 7 6 2 1
|
||||
1 3 2 4 5
|
||||
8 6 4 4 1
|
||||
1 3 6 7 9
|
83
02/main.cc
Normal file
83
02/main.cc
Normal file
|
@ -0,0 +1,83 @@
|
|||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
bool checkSequence(vector<int> nums) {
|
||||
// signals whether we are checking for greater or lower numbers
|
||||
// -1 - lower
|
||||
// 0 - no order yet
|
||||
// 1 - greater
|
||||
int greater = 0;
|
||||
int drag = nums[0];
|
||||
|
||||
for (int i = 1; i < nums.size(); i++) {
|
||||
// check difference first
|
||||
if (drag == nums[i] || drag - nums[i] > 3 || drag - nums[i] < -3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// check order
|
||||
if (greater == 0) {
|
||||
if (drag < nums[i]) greater = 1;
|
||||
else if (drag > nums[i]) greater = -1;
|
||||
}
|
||||
else if (greater > 0) {
|
||||
if (drag >= nums[i]) return false;
|
||||
}
|
||||
else if (greater < 0) {
|
||||
if (drag <= nums[i]) return false;
|
||||
}
|
||||
|
||||
drag = nums[i];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void lineToVector(string line, vector<int> &nums) {
|
||||
// stream for convenience
|
||||
stringstream line_stream;
|
||||
line_stream << line;
|
||||
|
||||
int a;
|
||||
|
||||
while (line_stream >> a) {
|
||||
nums.push_back(a);
|
||||
}
|
||||
}
|
||||
|
||||
bool checkSequenceDampened(vector<int> nums) {
|
||||
if (checkSequence(nums)) return true;
|
||||
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
int temp = nums[i];
|
||||
|
||||
nums.erase(nums.begin() + i);
|
||||
if (checkSequence(nums)) return true;
|
||||
nums.insert(nums.begin() + i , temp);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
ifstream input_stream("input");
|
||||
string line;
|
||||
int sum = 0;
|
||||
int dampened_sum = 0;
|
||||
|
||||
while (getline(input_stream, line)) {
|
||||
// convert line to int sequence
|
||||
vector<int> nums;
|
||||
lineToVector(line, nums);
|
||||
|
||||
if (checkSequence(nums)) sum++;
|
||||
if (checkSequenceDampened(nums)) dampened_sum++;
|
||||
}
|
||||
|
||||
cout << "number of safe lines is: " << sum << endl;
|
||||
cout << "number of safe lines (dampened) is: " << dampened_sum << endl;
|
||||
return 0;
|
||||
}
|
Loading…
Reference in a new issue