aboutsummaryrefslogtreecommitdiff
path: root/2017/src/day11.cpp
blob: ea945c16877a5af290a4e5505c38229d07058954 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

// see: https://www.redblobgames.com/grids/hexagons/

using namespace std;

namespace {

string
read_file(const filesystem::path& filename)
{
	ifstream file{ filename };
	string   line;
	getline(file, line);
	return line;
}

vector<string>
split(const string& line)
{
	stringstream   strm{ line };
	vector<string> data;

	for ( string word; getline(strm, word, ','); ) {
		data.emplace_back(word);
	}

	return data;
}

void
part1(const vector<string>& steps)
{
	// string => (q, s, r)
	map<string, tuple<int, int, int>> dirs{
		{ "n", { 0, 1, -1 } },
		{ "nw", { -1, 1, 0 } },
		{ "sw", { -1, 0, 1 } },
		{ "s", { 0, -1, 1 } },
		{ "se", { 1, -1, 0 } },
		{ "ne", { 1, 0, -1 } }
	};

	tuple<int, int, int> current = { 0, 0, 0 };
	for ( const auto& step: steps ) {
		const auto [dq, ds, dr] = dirs.at(step);

		get<0>(current) += dq;
		get<1>(current) += ds;
		get<2>(current) += dr;
	}

	auto dist = (abs(get<0>(current)) + abs(get<1>(current)) + abs(get<2>(current))) / 2;

	cout << "Part1: " << dist << '\n';
}

void
part2(const vector<string>& steps)
{
	// string => (q, s, r)
	map<string, tuple<int, int, int>> dirs{
		{ "n", { 0, 1, -1 } },
		{ "nw", { -1, 1, 0 } },
		{ "sw", { -1, 0, 1 } },
		{ "s", { 0, -1, 1 } },
		{ "se", { 1, -1, 0 } },
		{ "ne", { 1, 0, -1 } }
	};

	int max_dist = 0;

	tuple<int, int, int> current = { 0, 0, 0 };
	for ( const auto& step: steps ) {
		const auto [dq, ds, dr] = dirs.at(step);

		get<0>(current) += dq;
		get<1>(current) += ds;
		get<2>(current) += dr;

		auto dist = (abs(get<0>(current)) + abs(get<1>(current)) + abs(get<2>(current))) / 2;

		max_dist = max(max_dist, dist);
	}

	cout << "Part2: " << max_dist << '\n';
}

} // namespace

int
main()
{
	auto line  = read_file("data/day11.txt");
	auto steps = split(line);
	part1(steps);
	part2(steps);
}