diff options
Diffstat (limited to '2023/18/src/part1.cpp')
-rw-r--r-- | 2023/18/src/part1.cpp | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/2023/18/src/part1.cpp b/2023/18/src/part1.cpp new file mode 100644 index 0000000..b7c9e09 --- /dev/null +++ b/2023/18/src/part1.cpp | |||
@@ -0,0 +1,62 @@ | |||
1 | #include <iostream> | ||
2 | #include <fstream> | ||
3 | #include <sstream> | ||
4 | #include <deque> | ||
5 | #include <vector> | ||
6 | #include <tuple> | ||
7 | |||
8 | #include "util.h" | ||
9 | |||
10 | using Cmd = std::tuple<char,int>; | ||
11 | using Pos = std::pair<int,int>; | ||
12 | using Polygon = std::vector<Pos>; | ||
13 | |||
14 | std::vector<Cmd> parse(const char* file) | ||
15 | { | ||
16 | std::vector<Cmd> cmds; | ||
17 | if (std::ifstream input{ file }; input.is_open()) | ||
18 | { | ||
19 | char dir; int steps; | ||
20 | std::string line; | ||
21 | while (not std::getline(input,line).eof()) | ||
22 | { | ||
23 | std::stringstream in{ line }; | ||
24 | in >> dir >> steps; | ||
25 | cmds.push_back({ dir, steps }); | ||
26 | } | ||
27 | } | ||
28 | return cmds; | ||
29 | } | ||
30 | |||
31 | std::pair<int,Polygon> compute_border(Pos pos, const std::vector<Cmd>& cmds) | ||
32 | { | ||
33 | Polygon poly; | ||
34 | int border{}; | ||
35 | auto [x, y] = pos; | ||
36 | for(const auto& cmd : cmds) | ||
37 | { | ||
38 | auto [dir, steps] = cmd; | ||
39 | switch (dir) | ||
40 | { | ||
41 | case 'R': y += steps; break; | ||
42 | case 'D': x += steps; break; | ||
43 | case 'L': y -= steps; break; | ||
44 | case 'U': x -= steps; | ||
45 | } | ||
46 | poly.push_back({ x, y }); | ||
47 | border += steps; | ||
48 | } | ||
49 | return { border, std::move(poly) }; | ||
50 | } | ||
51 | |||
52 | |||
53 | |||
54 | int main(int argc, char* argv[]) | ||
55 | { | ||
56 | auto cmds = parse(argv[1]); | ||
57 | auto [border, polygon] = compute_border({ 0, 0 }, cmds); | ||
58 | int area = util::shoelace<int>(polygon.cbegin(), polygon.cend()); | ||
59 | |||
60 | std::cout << border + util::pick(area, border) << std::endl; | ||
61 | return 0; | ||
62 | } | ||