blob: 2bb2e78480245f0a2143204662b6e4c3cecc29d8 (
plain)
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
|
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
// JSON parsing
#include <nlohmann/json.hpp>
using namespace std;
using json = nlohmann::json;
string
read_file(string_view filename)
{
fstream input{ filename };
return { istreambuf_iterator{ input }, {} };
}
template<class UnaryFunction>
void
recursive_iterate(const json& j, UnaryFunction f) // NOLINT
{
for ( auto it = j.begin(); it != j.end(); ++it ) {
if ( it->is_structured() ) {
recursive_iterate(*it, f);
}
else {
f(it);
}
}
}
void
part1(string_view document)
{
auto json = json::parse(document);
long sum = 0;
recursive_iterate(json, [&](json::const_iterator iter) {
if ( iter.value().is_number() ) {
sum += iter.value().get<long>();
}
});
cout << sum << endl;
}
void
part2(string_view document)
{
json::parser_callback_t parser_callback = [](int /*depth*/, json::parse_event_t event, json& parsed) {
if ( event == json::parse_event_t::object_end ) {
for ( auto it = parsed.begin(); it != parsed.end(); ++it ) {
if ( it.value().is_string() && it.value().get<string>() == "red" ) {
return false;
}
}
}
return true;
};
auto json = json::parse(document, parser_callback);
long sum = 0;
recursive_iterate(json, [&](json::const_iterator iter) {
if ( iter.value().is_number() ) {
sum += iter.value().get<long>();
}
});
cout << sum << endl;
}
int
main()
{
auto document = read_file("data/day12.txt");
part1(document);
part2(document);
}
|