From 3300d3c35d2e228ea3774737c8cf551e6a18116f Mon Sep 17 00:00:00 2001 From: Matthew Gretton-Dann Date: Mon, 4 Dec 2023 09:25:16 +0000 Subject: [PATCH] 2023 Day 4 Part 1 --- 2023/puzzle-04-01.cc | 67 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 2023/puzzle-04-01.cc diff --git a/2023/puzzle-04-01.cc b/2023/puzzle-04-01.cc new file mode 100644 index 0000000..3f14040 --- /dev/null +++ b/2023/puzzle-04-01.cc @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using UInt = std::uint64_t; +using NumVec = std::vector; + +struct Card { + explicit Card(std::string line) { + assert(line.substr(0, 4) == "Card"); + line = line.substr(4); + + /* Get the ID. */ + std::size_t pos{0}; + id_ = std::stoull(line, &pos); + assert(line[pos] == ':'); + line = line.substr(pos + 1); + + /* Read in the winners. */ + while (line[0] != '|') { + winners_.push_back(std::stoull(line, &pos)); + while (line[pos] == ' ') { ++pos; } + line = line.substr(pos); + } + std::sort(winners_.begin(), winners_.end()); + + /* Read in the numbers we have. */ + line = line.substr(1); + while (!line.empty()) { + got_.push_back(std::stoull(line, &pos)); + line = line.substr(pos); + } + std::sort(got_.begin(), got_.end()); + } + + [[nodiscard]] auto score() const -> UInt { + NumVec intersection; + std::set_intersection(winners_.begin(), winners_.end(), got_.begin(), got_.end(), + std::back_inserter(intersection)); + return intersection.empty() ? 0 : (1 << (intersection.size() - 1)); + } + + UInt id_{0}; + NumVec got_; + NumVec winners_; +}; + +auto main() -> int try { + std::string line; + UInt total_score{0}; + while (std::getline(std::cin, line)) { + Card card(line); + total_score += card.score(); + } + + std::cout << "Score: " << total_score << '\n'; + return EXIT_SUCCESS; +} +catch (...) { + std::cerr << "Uncaught exception.\n"; + return EXIT_FAILURE; +}