Skip to content

Instantly share code, notes, and snippets.

@maudzekod4000
Created December 17, 2024 18:30
Show Gist options
  • Save maudzekod4000/43c6f7fbb4955bf34c9b1a6d2347cc55 to your computer and use it in GitHub Desktop.
Save maudzekod4000/43c6f7fbb4955bf34c9b1a6d2347cc55 to your computer and use it in GitHub Desktop.
AOC 2024 Problem 5 Part 1 N^2 * M Complexity? No problem for C++!
#include <iostream>
#include <fstream>
#include <string>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <sstream>
#include <regex>
#include <utility>
using namespace std;
// Complexity of N^2 * M ? No problem for C++!
bool checkForValidity(std::vector<std::pair<int, int>> rules, std::vector<int> pages)
{
// check all pairs of pages
for (int i = 0; i < pages.size(); i++) {
for (int j = i + 1; j < pages.size(); j++) {
int a = pages[i];
int b = pages[j];
for (int k = 0; k < rules.size(); k++) {
auto rule = rules[k];
if (rule.first == b && rule.second == a) {
return false;
}
}
}
}
return true;
}
int main()
{
ifstream infile("input.txt");
if (!infile.is_open()) {
cout << "File prob\n";
return -1;
}
string line;
std::vector<std::pair<int, int>> rules;
while (infile.good()) {
getline(infile, line);
if (line.empty()) break;
int x, y;
auto pos = line.find('|');
std::string firstNumS = line.substr(0, pos);
std::string secondNumS = line.substr(pos + 1);
int page1 = std::stoi(firstNumS);
int page2 = std::stoi(secondNumS);
rules.emplace_back(page1, page2);
}
int total = 0;
while (infile.good()) {
getline(infile, line);
if (line.empty()) break;
std::vector<int> pages;
char separator = ',';
int offset = 0;
int pos;
do {
pos = line.find(separator, offset);
std::string str = line.substr(offset, pos - offset);
pages.push_back(std::stoi(str));
offset = pos + 1;
} while (pos != std::string::npos);
auto isvalid = checkForValidity(rules, pages);
if (isvalid) {
int mid = pages[pages.size() / 2];
total += mid;
}
}
std::cout << total << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment