day2 part one done

This commit is contained in:
PoliEcho 2024-12-12 21:31:11 +01:00
parent deafcf3662
commit 7f4d2d5acb

View File

@ -25,9 +25,6 @@ int main() {
int res = 0;
if (inputfile.is_open()) {
// Read each line from the file and store it in the
// 'line' variable.
std::string line;
std::vector<std::string> num_s;
std::vector<int> num;
@ -35,56 +32,49 @@ int main() {
while (std::getline(inputfile, line)) {
num_s = splitString(line);
num.clear();
// Convert strings to integers
std::transform(num_s.begin(), num_s.end(), std::back_inserter(num),
[](const std::string &s) { return std::stoi(s); });
// decreasing
bool safe = true;
int old_n = -1;
for (int n : num) {
if (old_n == -1) {
old_n = n;
continue;
}
if ((old_n - n) > 2 || (old_n - n) < 0 || old_n == n) {
for (size_t i = 1; i < num.size(); ++i) {
int diff = num[i - 1] - num[i];
if (diff < 1 || diff > 3) {
safe = false;
break;
}
old_n = n;
}
if (safe) {
res++;
std::cerr << line << "\n";
std::clog << line << std::endl;
continue;
}
// increasing
safe = true;
old_n = -1;
for (int n : num) {
if (old_n == -1) {
old_n = n;
continue;
}
if ((n - old_n) > 3 || (n - old_n) < 0 || old_n == n) {
for (size_t i = 1; i < num.size(); ++i) {
int diff = num[i] - num[i - 1];
if (diff < 1 || diff > 3) {
safe = false;
break;
}
old_n = n;
}
if (safe) {
std::cerr << line << "\n";
std::clog << line << std::endl;
res++;
}
}
// Close the file stream once all lines have been
// read.
inputfile.close();
} else {
// Print an error message to the standard error
// stream if the file cannot be opened.
std::cerr << "Unable to open file!" << std::endl;
return ENOENT;
}
std::cout << "\n\n" << res << "\n\n";
std::cout << res << std::endl;
return 0;
}
}