1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
#include <cctype>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<string>
split(const string& line, char sep)
{
vector<string> parts{};
stringstream input{ line };
for ( string part; getline(input, part, sep); ) {
parts.emplace_back(part);
}
return parts;
}
void
part1()
{
fstream input{ "data/day02.txt" };
auto sum = 0;
for ( string line; getline(input, line); ) {
auto game = split(line, ':');
auto gameId = 0;
sscanf(game[0].data(), "Game %d", &gameId); // NOLINT
auto subsets = split(game[1], ';');
auto fail = false;
for ( const auto& subset: subsets ) {
auto cubes = split(subset, ',');
map<string, int> counts{};
for ( const auto& cube: cubes ) {
auto data = split(cube, ' ');
auto count = stoi(data[1]);
auto color = data[2];
counts[color] += count;
}
fail |= (counts["red"] > 12) || (counts["green"] > 13) || (counts["blue"] > 14); // NOLINT
}
if ( !fail ) {
sum += gameId;
}
}
cout << sum << endl;
}
void
part2()
{
fstream input{ "data/day02.txt" };
auto sum = 0;
for ( string line; getline(input, line); ) {
auto game = split(line, ':');
auto subsets = split(game[1], ';');
map<string, int> colors{};
for ( const auto& subset: subsets ) {
auto cubes = split(subset, ',');
for ( const auto& cube: cubes ) {
auto data = split(cube, ' ');
auto count = stoi(data[1]);
auto color = data[2];
colors[color] = max(colors[color], count);
}
}
sum += colors["red"] * colors["green"] * colors["blue"];
}
cout << sum << endl;
}
int
main()
{
part1();
part2();
}
|