venyanwarrior

AoC 2024 - Day 2 Part 1

Dec 25th, 2024 (edited)
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | Source Code | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <sstream>
  6.  
  7. bool isLevelValid(std::string level);
  8. bool isNotInRange(int num1, int num2);
  9.  
  10. int main() {
  11.     std::ifstream infile;
  12.  
  13.     infile.open("../input.txt");
  14.     if (!infile.is_open()) {
  15.         std::cout << "Input file opening failed." << std::endl;
  16.     }
  17.  
  18.     std::vector<std::string> fileData;
  19.  
  20.     for (u_int i = 0; !infile.eof(); i++) {
  21.         fileData.push_back("");
  22.         getline(infile, fileData.at(i));
  23.     }
  24.  
  25.     int numSafeReports = 0;
  26.     for (std::string level : fileData) {
  27.         if (isLevelValid(level)) {
  28.             std::cout << "Safe" << std::endl;
  29.             numSafeReports++;
  30.         } else {
  31.             std::cout << "Unsafe" << std::endl;
  32.         }
  33.     }
  34.  
  35.     std::cout << "Safe reports: " << numSafeReports << std::endl;
  36.  
  37. }
  38.  
  39. bool isLevelValid(std::string level) {
  40.  
  41.     std::stringstream ss(level);
  42.     std::vector<int> levelNums;
  43.     std::string currentNum;
  44.  
  45.     while (std::getline(ss, currentNum, ' ')) {
  46.         levelNums.push_back(stoi(currentNum));
  47.     }
  48.  
  49.     bool ascendingOrDescending = false;
  50.     //*Check if the level is in ascending order
  51.     if (std::is_sorted(levelNums.begin(), levelNums.end())) {
  52.         ascendingOrDescending = true;
  53.     }
  54.  
  55.     //*Check if the level is in descending order
  56.     std::reverse(levelNums.begin(), levelNums.end());
  57.     if (std::is_sorted(levelNums.begin(), levelNums.end())) {
  58.         ascendingOrDescending = true;
  59.     }
  60.     std::reverse(levelNums.begin(), levelNums.end()); //Reverse back to normal
  61.  
  62.     if (ascendingOrDescending == false) {
  63.         return false;
  64.     }
  65.  
  66.     //*Check that no two values are the same
  67.     if (std::adjacent_find(levelNums.begin(), levelNums.end()) != levelNums.end()) {
  68.         return false;
  69.     }
  70.  
  71.     //*Check that adjacent values differ by 1-3
  72.     if (std::adjacent_find(levelNums.begin(), levelNums.end(), isNotInRange) != levelNums.end()) {
  73.         return false;
  74.     }
  75.  
  76.     //* If all tests pass, the level is safe
  77.     return true;
  78. }
  79.  
  80. bool isNotInRange(int num1, int num2) {
  81.     if ((abs(num1 - num2) < 1) || (abs(num1 - num2) > 3)) {
  82.         return true;
  83.     }
  84.     return false;
  85. }
Add Comment
Please, Sign In to add comment