diff options
Diffstat (limited to '2023/08/src/part1.cpp')
-rw-r--r-- | 2023/08/src/part1.cpp | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/2023/08/src/part1.cpp b/2023/08/src/part1.cpp new file mode 100644 index 0000000..9585536 --- /dev/null +++ b/2023/08/src/part1.cpp | |||
@@ -0,0 +1,70 @@ | |||
1 | #include <iostream> | ||
2 | #include <fstream> | ||
3 | #include <sstream> | ||
4 | #include <unordered_map> | ||
5 | #include <vector> | ||
6 | |||
7 | #include "util.h" | ||
8 | |||
9 | using Moves = std::vector<bool>; | ||
10 | using Map = std::unordered_map<int,std::pair<int,int>>; | ||
11 | |||
12 | constexpr char EQUAL[] = "="; | ||
13 | |||
14 | int encode(std::string str) | ||
15 | { | ||
16 | int res{}; | ||
17 | for (unsigned char c : str) | ||
18 | { | ||
19 | if ('A' <= c and c <= 'Z') | ||
20 | { | ||
21 | res *= 1 + 'Z' - 'A'; | ||
22 | res += c - 'A'; | ||
23 | } | ||
24 | } | ||
25 | return res; | ||
26 | } | ||
27 | |||
28 | std::pair<Moves,Map> parse(const char* path) | ||
29 | { | ||
30 | Map map{}; | ||
31 | Moves moves{}; | ||
32 | |||
33 | std::ifstream input{ path }; | ||
34 | if (input.is_open()) | ||
35 | { | ||
36 | std::string line; | ||
37 | std::getline(input,line); | ||
38 | |||
39 | moves.resize(line.size()); | ||
40 | std::transform(line.cbegin(), line.cend(), | ||
41 | moves.begin(), [](unsigned char c) { return c == 'L'; }); | ||
42 | |||
43 | std::string from, tol, tor; | ||
44 | while (not std::getline(input,line).eof()) | ||
45 | { | ||
46 | if (line.empty()) continue; | ||
47 | |||
48 | std::istringstream in{ line }; | ||
49 | in >> from >> util::skip<EQUAL> >> tol >> tor; | ||
50 | map.insert({ encode(from), { encode(tol), encode(tor) } }); | ||
51 | } | ||
52 | } | ||
53 | input.close(); | ||
54 | |||
55 | return { std::move(moves), std::move(map) }; | ||
56 | } | ||
57 | |||
58 | int main(int argc, char* argv[]) | ||
59 | { | ||
60 | int answer{}; | ||
61 | |||
62 | auto [moves, map] = parse(argv[1]); | ||
63 | |||
64 | for (int pos = encode("AAA"); | ||
65 | pos != encode("ZZZ"); | ||
66 | pos = moves[answer++ % moves.size()] ? map[pos].first : map[pos].second); | ||
67 | |||
68 | std::cout << answer << std::endl; | ||
69 | return 0; | ||
70 | } | ||