+day05 part1
This commit is contained in:
parent
3e3ba0fa3e
commit
2a202242d8
2 changed files with 1472 additions and 0 deletions
1379
2024/day05/input
Normal file
1379
2024/day05/input
Normal file
File diff suppressed because it is too large
Load diff
93
2024/day05/part1.cc
Normal file
93
2024/day05/part1.cc
Normal file
|
@ -0,0 +1,93 @@
|
|||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
class print_job {
|
||||
std::vector<int> page_order;
|
||||
std::set<int> pages;
|
||||
public:
|
||||
print_job(std::stringstream& ss);
|
||||
bool before(int before, int after) const;
|
||||
bool contains(int page) const;
|
||||
int middle() const;
|
||||
};
|
||||
|
||||
print_job::print_job(std::stringstream& ss) {
|
||||
int page;
|
||||
while (ss >> page) {
|
||||
page_order.emplace_back(page);
|
||||
pages.emplace(page);
|
||||
ss.ignore(1, ',');
|
||||
}
|
||||
}
|
||||
|
||||
bool print_job::before(int before, int after) const {
|
||||
return std::distance(page_order.begin(), std::find(page_order.begin(), page_order.end(), before))
|
||||
< std::distance(page_order.begin(), std::find(page_order.begin(), page_order.end(), after));
|
||||
}
|
||||
|
||||
bool print_job::contains(int page) const {
|
||||
return pages.contains(page);
|
||||
}
|
||||
|
||||
int print_job::middle() const {
|
||||
return page_order[page_order.size() / 2];
|
||||
}
|
||||
|
||||
class rule {
|
||||
int before;
|
||||
int after;
|
||||
public:
|
||||
rule(std::stringstream& ss);
|
||||
bool valid(const print_job& job) const;
|
||||
};
|
||||
|
||||
rule::rule(std::stringstream& ss) {
|
||||
ss >> before;
|
||||
ss.ignore(1, '|');
|
||||
ss >> after;
|
||||
}
|
||||
|
||||
bool rule::valid(const print_job& job) const {
|
||||
return !job.contains(before) || !job.contains(after) || job.before(before, after);
|
||||
}
|
||||
|
||||
class rule_set {
|
||||
std::vector<rule> rules;
|
||||
public:
|
||||
rule_set(std::istream& is);
|
||||
bool valid(const print_job& job) const;
|
||||
};
|
||||
|
||||
rule_set::rule_set(std::istream& is) {
|
||||
std::string line;
|
||||
while (std::getline(is, line)) {
|
||||
if (line == "") {
|
||||
return;
|
||||
}
|
||||
std::stringstream ss(line);
|
||||
rules.emplace_back(ss);
|
||||
}
|
||||
}
|
||||
|
||||
bool rule_set::valid(const print_job& job) const {
|
||||
return std::ranges::all_of(rules, [&](auto rule) { return rule.valid(job); });
|
||||
}
|
||||
|
||||
int main() {
|
||||
rule_set rules(std::cin);
|
||||
std::string line;
|
||||
int sum = 0;
|
||||
while (std::getline(std::cin, line)) {
|
||||
std::stringstream ss(line);
|
||||
print_job job(ss);
|
||||
if (rules.valid(job)) {
|
||||
sum += job.middle();
|
||||
}
|
||||
}
|
||||
std::cout << sum << std::endl;
|
||||
return EXIT_SUCCESS;
|
||||
}
|
Loading…
Add table
Reference in a new issue