aboutsummaryrefslogtreecommitdiff
path: root/2018/src/day08.cpp
blob: 9c2a0933dcfa87055fccfddcd3ad583eccc1505b (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
79
80
81
82
83
84
85
86
87
88
#include <filesystem>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

namespace {

vector<int>
read_file(const filesystem::path& filename)
{
	ifstream    file{ filename };
	vector<int> data;

	for ( int number{}; file >> number; ) {
		data.emplace_back(number);
	}

	return data;
}

void
part1(const vector<int>& data)
{
	size_t idx = 0;
	int    sum = 0;

	function<void()> func = [&] {
		auto count_child = data.at(idx++);
		auto count_meta  = data.at(idx++);

		while ( count_child-- > 0 ) {
			func();
		}

		while ( count_meta-- > 0 ) {
			sum += data.at(idx++);
		}
	};

	func();

	cout << "Part 1: " << sum << '\n';
}

void
part2(const vector<int>& data)
{
	size_t idx = 0;

	function<int()> func = [&] {
		const auto count_child = data.at(idx++);
		const auto count_meta  = data.at(idx++);

		vector<int> child_values;
		for ( int i = 0; i != count_child; ++i ) {
			child_values.emplace_back(func());
		}

		int value = 0;
		for ( int i = 0; i != count_meta; ++i ) {
			auto meta = data.at(idx++);
			if ( count_child == 0 ) {
				value += meta;
			}
			else {
				meta--;
				if ( meta >= 0 && meta < count_child ) {
					value += child_values[static_cast<size_t>(meta)];
				}
			}
		}
		return value;
	};

	cout << "Part 2: " << func() << '\n';
}

} // namespace

int
main()
{
	auto data = read_file("data/day08.txt");
	part1(data);
	part2(data);
}