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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
#include <array>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
vector<string>
split(string_view line, string_view delimiter)
{
size_t pos_start = 0;
size_t pos_end = 0;
vector<string> res;
while ( (pos_end = line.find(delimiter, pos_start)) != string::npos ) {
auto token = line.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delimiter.length();
res.emplace_back(token);
}
if ( pos_start != line.size() ) {
res.emplace_back(line.substr(pos_start));
}
return res;
}
vector<tuple<char, long>>
read_file(const string& filename)
{
fstream input{ filename };
string content{ istreambuf_iterator<char>{ input }, istreambuf_iterator<char>{} };
vector<tuple<char, long>> result;
for ( const auto& part: split(content, ", ") ) {
result.emplace_back(part[0], stol(part.substr(1)));
}
return result;
}
void
part1(const vector<tuple<char, long>>& input)
{
array<tuple<long, long>, 4> dirs = {
make_tuple(1L, 0L),
make_tuple(0L, 1L),
make_tuple(-1L, 0L),
make_tuple(0L, -1L)
};
size_t dir = 0;
long pos_x = 0;
long pos_y = 0;
for ( const auto& [change, length]: input ) {
if ( change == 'L' ) {
dir = (dir + 1) % 4;
}
else {
dir = (dir + 3) % 4;
}
auto [delta_x, delta_y] = dirs.at(dir);
pos_x += length * delta_x;
pos_y += length * delta_y;
}
cout << abs(pos_x) + abs(pos_y) << endl;
}
void
part2(const vector<tuple<char, long>>& input)
{
array<tuple<long, long>, 4> dirs = {
make_tuple(1L, 0L),
make_tuple(0L, 1L),
make_tuple(-1L, 0L),
make_tuple(0L, -1L)
};
size_t dir = 0;
long pos_x = 0;
long pos_y = 0;
set<tuple<long, long>> visited;
for ( auto [change, length]: input ) {
if ( change == 'L' ) {
dir = (dir + 1) % 4;
}
else {
dir = (dir + 3) % 4;
}
auto [delta_x, delta_y] = dirs.at(dir);
while ( length-- > 0 ) {
pos_x += delta_x;
pos_y += delta_y;
if ( visited.contains({ pos_x, pos_y }) ) {
cout << abs(pos_x) + abs(pos_y) << endl;
return;
}
visited.emplace(pos_x, pos_y);
}
}
}
int
main()
{
auto input = read_file("data/day01.txt");
part1(input);
part2(input);
}
|