PB4 part2 done
This commit is contained in:
parent
927b7ee529
commit
323e2ade2f
7
main.cpp
7
main.cpp
@ -29,5 +29,12 @@ int main() {
|
||||
std::cout << "Problem 4 part 1: " << result << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::cout << "Begin Problem 4 part 2\n";
|
||||
if (const auto result = pb4::problem_part2("inputs/pb4.txt"); result != 0) {
|
||||
std::cout << "Problem 4 part 2: " << result << '\n';
|
||||
}
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
@ -7,6 +7,7 @@
|
||||
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
@ -72,3 +73,53 @@ std::size_t pb4::problem_part1(const std::filesystem::path &problemFile) noexcep
|
||||
}
|
||||
return std::accumulate(compute_points.cbegin(), compute_points.cend(), 0);
|
||||
}
|
||||
|
||||
std::size_t pb4::problem_part2(const std::filesystem::path &problemFile) noexcept {
|
||||
auto file_opt = common::read_file(problemFile);
|
||||
if (!file_opt) {
|
||||
return 0;
|
||||
}
|
||||
std::ifstream &file = *file_opt;
|
||||
std::string line;
|
||||
std::unordered_map<int, int> matching_number;
|
||||
int i = 1;
|
||||
while (std::getline(file, line)) {
|
||||
if (!line.empty()) {
|
||||
line = line.substr(line.find_first_of(':') + 1);
|
||||
|
||||
const auto split_char = line.find_first_of('|');
|
||||
const auto left = line.substr(0, split_char);
|
||||
const auto right = line.substr(split_char + 1);
|
||||
|
||||
const auto left_cards = extract_unique_cards(left);
|
||||
const auto right_cards = extract_unique_cards(right);
|
||||
std::vector<int> intersection;
|
||||
intersection.reserve(left.size() + right_cards.size());
|
||||
std::set_intersection(left_cards.cbegin(),
|
||||
left_cards.cend(),
|
||||
right_cards.cbegin(),
|
||||
right_cards.cend(),
|
||||
std::back_inserter(intersection));
|
||||
|
||||
const int inter_size = static_cast<int>(intersection.size());
|
||||
if (matching_number.contains(i)) {
|
||||
matching_number[i] += 1;
|
||||
} else {
|
||||
matching_number.emplace(i, 1);
|
||||
}
|
||||
for (int j = 1; j <= inter_size; ++j) {
|
||||
const int next_match = i + j;
|
||||
if (!matching_number.contains(next_match)) {
|
||||
matching_number.emplace(next_match, matching_number.at(i));
|
||||
} else {
|
||||
matching_number[next_match] += matching_number.at(i);
|
||||
}
|
||||
}
|
||||
++i;
|
||||
}
|
||||
}
|
||||
return std::accumulate(matching_number.cbegin(),
|
||||
matching_number.cend(),
|
||||
0,
|
||||
[](const auto input, const auto &bPair) -> int { return input + bPair.second; });
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user