aboutsummaryrefslogtreecommitdiff
path: root/2017/src/day19.cpp
diff options
context:
space:
mode:
Diffstat (limited to '2017/src/day19.cpp')
-rw-r--r--2017/src/day19.cpp97
1 files changed, 97 insertions, 0 deletions
diff --git a/2017/src/day19.cpp b/2017/src/day19.cpp
new file mode 100644
index 0000000..470bb4f
--- /dev/null
+++ b/2017/src/day19.cpp
@@ -0,0 +1,97 @@
1#include <filesystem>
2#include <fstream>
3#include <iostream>
4#include <map>
5#include <string>
6#include <tuple>
7
8using namespace std;
9
10namespace {
11
12using dir_type = tuple<size_t, size_t>;
13using pos_type = tuple<size_t, size_t>;
14using puzzle_type = map<pos_type, char>;
15
16puzzle_type
17read_file(const filesystem::path& filename)
18{
19 ifstream file{ filename };
20 puzzle_type data;
21
22 size_t row = 0;
23 for ( string line; getline(file, line); ) {
24 for ( size_t col = 0; col != line.size(); ++col ) {
25 if ( line.at(col) != ' ' ) {
26 data.emplace(pos_type{ col, row }, line.at(col));
27 }
28 }
29 ++row;
30 }
31
32 return data;
33}
34
35pos_type
36find_start(const puzzle_type& puzzle)
37{
38 for ( size_t col = 0;; ++col ) {
39 const pos_type pos{ col, 0 };
40 if ( puzzle.contains(pos) && puzzle.at(pos) == '|' ) {
41 return pos;
42 }
43 }
44}
45
46void
47solve(const puzzle_type& puzzle)
48{
49 string result;
50 size_t steps = 0;
51
52 pos_type pos = find_start(puzzle);
53 dir_type dir{ 0, 1 };
54
55 while ( puzzle.contains(pos) ) {
56 auto chr = puzzle.at(pos);
57
58 if ( chr >= 'A' && chr <= 'Z' ) {
59 result += chr;
60 }
61 else if ( chr == '+' ) {
62 auto [dx, dy] = dir;
63 auto left = dir_type{ -dy, dx };
64 auto right = dir_type{ dy, -dx };
65
66 pos_type next_left = { get<0>(pos) + get<0>(left), get<1>(pos) + get<1>(left) };
67 pos_type next_right = { get<0>(pos) + get<0>(right), get<1>(pos) + get<1>(right) };
68
69 if ( puzzle.contains(next_left) ) {
70 dir = left;
71 }
72 else if ( puzzle.contains(next_right) ) {
73 dir = right;
74 }
75 else {
76 cerr << "Error!\n";
77 return;
78 }
79 }
80
81 get<0>(pos) += get<0>(dir);
82 get<1>(pos) += get<1>(dir);
83 ++steps;
84 }
85
86 cout << "Part1: " << result << '\n';
87 cout << "Part2: " << steps << '\n';
88}
89
90} // namespace
91
92int
93main()
94{
95 auto puzzle = read_file("data/day19.txt");
96 solve(puzzle);
97}