-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdayTwo.cpp
More file actions
86 lines (77 loc) · 2.17 KB
/
dayTwo.cpp
File metadata and controls
86 lines (77 loc) · 2.17 KB
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
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
namespace DayTwo
{
namespace {
using std::string;
const int kMinDiff = 1; // google's constant naming convention is kPascalCase
const int kMaxDiff = 3;
const char kDelim = ' ';
bool twoLevelsAreSafe(const int& parsedInt, const int& previousLevel, const bool& comparisonIsLargerThan)
{
int diff = parsedInt - previousLevel;
if (abs(diff) < kMinDiff or abs(diff) > kMaxDiff)
{
// std::cout << "distance: " << previousLevel << '-' << parsedInt << std::endl;
return false;
}
if (comparisonIsLargerThan)
{
if (diff < 0) {
// std::cout << "comparison: " << previousLevel << '-' << parsedInt << std::endl;
return false;
};
}
else
{
if (diff > 0) {
// std::cout << "comparison: " << previousLevel << '-' << parsedInt << std::endl;
return false;
}
}
return true;
}
bool handleLine(const std::string& line) { // actual source value is passed but cannot be edited
std::stringstream ss(line);
bool comparisonIsLargerThan = true;
string stringPart;
if (getline(ss, stringPart, kDelim)) {
int previousLevel = std::stoi(stringPart);
if (getline(ss, stringPart, kDelim))
{
int parsedInt = std::stoi(stringPart);
comparisonIsLargerThan = (parsedInt - previousLevel) > 0;
if (!twoLevelsAreSafe(parsedInt, previousLevel, comparisonIsLargerThan)) return false;
previousLevel = parsedInt;
}
while (getline(ss, stringPart, kDelim)) {
int parsedInt = std::stoi(stringPart);
if (!twoLevelsAreSafe(parsedInt, previousLevel, comparisonIsLargerThan)) return false;
previousLevel = parsedInt;
}
}
return true;
}
}
void dayTwo() {
std::cout << "Running program dayTwo" << '\n';
std::string line;
std::ifstream inputFile("dayTwoFull.txt");
if (inputFile.is_open())
{
int safeLines = 0;
while (getline(inputFile, line)) {
if (handleLine(line)) {
safeLines++;
// std::cout << line << '\n';
};
}
std::cout << "Safe lines:" << safeLines << '\n';
std::cout << "done reading file\n";
}
else std::cout << "Unable to open file";
}
}