summaryrefslogtreecommitdiff
path: root/2023/02/src/game.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2023/02/src/game.cpp')
-rw-r--r--2023/02/src/game.cpp98
1 files changed, 98 insertions, 0 deletions
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 @@
1#include "game.h"
2
3#include <iostream>
4#include <sstream>
5
6Game::Game(int id) : id_{ id }
7{
8}
9
10void Game::push_back(const std::vector<int>& draw)
11{
12 draws.push_back(draw);
13}
14
15bool Game::is_valid(int blue, int red, int green) const
16{
17 for (const auto& draw : draws)
18 {
19 if (draw[0] > blue or draw[1] > red or draw[2] > green)
20 {
21 return false;
22 }
23 }
24 return true;
25}
26
27int Game::power() const
28{
29 int blue{}, red{}, green{};
30 for (const auto& draw : draws)
31 {
32 blue = std::max(draw[0], blue);
33 red = std::max(draw[1], red);
34 green = std::max(draw[2], green);
35 }
36
37 return blue * red * green;
38}
39
40std::string Game::to_string() const
41{
42 std::ostringstream out;
43 out << "Game " << id_ << ": ";
44 for (const auto& draw : draws)
45 {
46 out << draw[0] << " " << draw[1] << " " << draw[2] << ";";
47 }
48
49 return out.str();
50}
51
52Game Game::from_string(const std::string& line)
53{
54 std::istringstream in(line);
55
56 std::string id;
57 in >> skip<game_t> >> id;
58 id.pop_back();
59 Game game{ std::stoi(id) };
60
61 int n;
62 std::string kind;
63 std::vector<int> draw{ 0, 0, 0};
64
65 while (in >> n >> kind)
66 {
67 char sep{ kind.back() };
68 if (sep == ';' or sep == ',')
69 {
70 kind.pop_back();
71 }
72 else
73 {
74 sep = ';';
75 }
76
77 if (kind == "blue")
78 {
79 draw[0] += n;
80 }
81 else if (kind == "red")
82 {
83 draw[1] += n;
84 }
85 else if (kind == "green")
86 {
87 draw[2] += n;
88 }
89
90 if (sep == ';')
91 {
92 game.push_back(draw);
93 draw = { 0, 0, 0 };
94 }
95 }
96
97 return game;
98}