aoc2024 day 2
unknown
c_cpp
5 months ago
3.2 kB
3
Indexable
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cmath> int main() { std::ifstream inputFile("aoc24.txt"); if (!inputFile) { std::cerr << "Error: Could not open file!" << std::endl; return 1; } std::vector<std::vector<int>> dataset; std::string line; // Read the dataset from the file while (std::getline(inputFile, line)) { if (line.empty()) continue; std::istringstream lineStream(line); std::vector<int> row; int number; while (lineStream >> number) { row.push_back(number); } if (!row.empty()) { dataset.push_back(row); } } inputFile.close(); int counter = 0; // Counter for valid rows // Process each row in the dataset for (const auto& row : dataset) { if (row.size() < 2) continue; // Skip rows with fewer than 2 elements bool ascend = true; bool descend = true; bool safeDiffer = true; // Check the row's validity without removing any element for (size_t j = 0; j < row.size() - 1; ++j) { if (row[j] < row[j + 1]) { descend = false; } if (row[j] > row[j + 1]) { ascend = false; } int distance = abs(row[j] - row[j + 1]); if (distance < 1 || distance >= 4) { safeDiffer = false; } } // If the row is valid without any removal, increment the counter if (safeDiffer && (ascend || descend)) { ++counter; continue; // Skip the pop-checking part for this row } //flag bool validVariation = false; // Now check if removing any one element makes the row valid for (size_t pop = 0; pop < row.size(); ++pop) { std::vector<int> row_pop = row; // Copy the original row row_pop.erase(row_pop.begin() + pop); // Remove one element // Flags to track validity for the modified row (reset each time) ascend = true; descend = true; safeDiffer = true; //pop debug // Check the validity of the row after one element is removed for (size_t j = 0; j < row_pop.size() - 1; ++j) { if (row_pop[j] < row_pop[j + 1]) { descend = false; } if (row_pop[j] > row_pop[j + 1]) { ascend = false; } int distance = abs(row_pop[j] - row_pop[j + 1]); if (distance < 1 || distance >= 4) { safeDiffer = false; } } // If the modified row is valid, increment the counter and break if (safeDiffer && (ascend || descend)) { ++counter; break; // Exit the loop as we found a valid modified row } } } std::cout << "Number of valid rows: " << counter << std::endl; return 0; }
Editor is loading...
Leave a Comment