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