summaryrefslogtreecommitdiff
path: root/2023/18/src/part2.cpp
diff options
context:
space:
mode:
authorFederico Igne <undyamon@disroot.org>2023-12-19 02:06:02 +0100
committerFederico Igne <undyamon@disroot.org>2023-12-19 02:06:02 +0100
commite3c9f0c73077de51167491ca1ba4d5ccba005435 (patch)
tree792f18313a1e1fdbe2d0e97356631acd7ca65386 /2023/18/src/part2.cpp
parentfe385ca1e5cd219478aef8f982d07182e4c8ad0d (diff)
downloadaoc-e3c9f0c73077de51167491ca1ba4d5ccba005435.tar.gz
aoc-e3c9f0c73077de51167491ca1ba4d5ccba005435.zip
aoc(2318): Lavaduct Lagoon
Diffstat (limited to '2023/18/src/part2.cpp')
-rw-r--r--2023/18/src/part2.cpp63
1 files changed, 63 insertions, 0 deletions
diff --git a/2023/18/src/part2.cpp b/2023/18/src/part2.cpp
new file mode 100644
index 0000000..e9b6c02
--- /dev/null
+++ b/2023/18/src/part2.cpp
@@ -0,0 +1,63 @@
1#include <iostream>
2#include <fstream>
3#include <sstream>
4#include <vector>
5#include <tuple>
6
7#include "util.h"
8
9enum Dir { R = 0, D, L, U };
10using Cmd = std::tuple<Dir,long>;
11using Pos = std::pair<long,long>;
12using Polygon = std::vector<Pos>;
13
14std::vector<Cmd> parse(const char* file)
15{
16 std::vector<Cmd> cmds;
17 if (std::ifstream input{ file }; input.is_open())
18 {
19 Dir dir; int steps; std::string color;
20 std::string line;
21 while (not std::getline(input,line).eof())
22 {
23 std::stringstream in{ line };
24 in >> util::skip<char> >> util::skip<int> >> color;
25 steps = std::stoi(color.substr(2, 5), nullptr, 16);
26 dir = static_cast<Dir>(std::stoi(color.substr(7, 1)));
27 cmds.push_back({ dir, steps });
28 }
29 }
30 return cmds;
31}
32
33std::pair<long,Polygon> compute_border(Pos pos, const std::vector<Cmd>& cmds)
34{
35 Polygon poly;
36 long border{};
37 auto [x, y] = pos;
38 for(const auto& cmd : cmds)
39 {
40 auto [dir, steps] = cmd;
41 switch (dir)
42 {
43 case R: y += steps; break;
44 case D: x += steps; break;
45 case L: y -= steps; break;
46 case U: x -= steps;
47 }
48 poly.push_back({ x, y });
49 border += steps;
50 }
51 return { border, std::move(poly) };
52}
53
54int main(int argc, char* argv[])
55{
56 auto cmds = parse(argv[1]);
57 auto [border, polygon] = compute_border({ 0, 0 }, cmds);
58 long area = util::shoelace<long>(polygon.cbegin(), polygon.cend());
59
60 std::cout << border + util::pick(area, border) << std::endl;
61 return 0;
62}
63