From baaa6cd61c302c80c664e9aaa5e4ab2ab157b5cf Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Sun, 3 Dec 2023 18:57:02 +0100 Subject: aoc(2302): Cube Conundrum --- 2023/02/src/game.cpp | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 2023/02/src/game.cpp (limited to '2023/02/src/game.cpp') diff --git a/2023/02/src/game.cpp b/2023/02/src/game.cpp new file mode 100644 index 0000000..a99b8a2 --- /dev/null +++ b/2023/02/src/game.cpp @@ -0,0 +1,98 @@ +#include "game.h" + +#include +#include + +Game::Game(int id) : id_{ id } +{ +} + +void Game::push_back(const std::vector& draw) +{ + draws.push_back(draw); +} + +bool Game::is_valid(int blue, int red, int green) const +{ + for (const auto& draw : draws) + { + if (draw[0] > blue or draw[1] > red or draw[2] > green) + { + return false; + } + } + return true; +} + +int Game::power() const +{ + int blue{}, red{}, green{}; + for (const auto& draw : draws) + { + blue = std::max(draw[0], blue); + red = std::max(draw[1], red); + green = std::max(draw[2], green); + } + + return blue * red * green; +} + +std::string Game::to_string() const +{ + std::ostringstream out; + out << "Game " << id_ << ": "; + for (const auto& draw : draws) + { + out << draw[0] << " " << draw[1] << " " << draw[2] << ";"; + } + + return out.str(); +} + +Game Game::from_string(const std::string& line) +{ + std::istringstream in(line); + + std::string id; + in >> skip >> id; + id.pop_back(); + Game game{ std::stoi(id) }; + + int n; + std::string kind; + std::vector draw{ 0, 0, 0}; + + while (in >> n >> kind) + { + char sep{ kind.back() }; + if (sep == ';' or sep == ',') + { + kind.pop_back(); + } + else + { + sep = ';'; + } + + if (kind == "blue") + { + draw[0] += n; + } + else if (kind == "red") + { + draw[1] += n; + } + else if (kind == "green") + { + draw[2] += n; + } + + if (sep == ';') + { + game.push_back(draw); + draw = { 0, 0, 0 }; + } + } + + return game; +} -- cgit v1.2.3