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
|
#include <array>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <numeric>
using namespace std;
struct Generator {
explicit Generator(string_view init)
: values_(init)
, iter_(values_.begin())
{
}
size_t next()
{
size_t gen = (*iter_ == 'L') ? 0 : 1;
++iter_;
if ( iter_ == values_.end() ) {
iter_ = values_.begin();
}
return gen;
}
string values_;
string::iterator iter_;
};
void
part1()
{
fstream input{ "data/day08.txt" };
string line;
getline(input, line);
Generator generator{ line };
map<string, array<string, 2>> puzzle;
const regex pattern{ R"((.*) = \((.*), (.*)\))" };
while ( getline(input, line) ) {
if ( line.empty() ) {
continue;
}
smatch sub_match;
if ( regex_search(line, sub_match, pattern) ) {
puzzle[sub_match[1]] = { sub_match[2], sub_match[3] };
}
}
auto counter = 0;
for ( string str{ "AAA" }; str != "ZZZ"; str = puzzle[str][generator.next()] ) {
++counter;
}
cout << counter << endl;
}
void
part2()
{
fstream input{ "data/day08.txt" };
string firstline;
getline(input, firstline);
map<string, array<string, 2>> puzzle;
const regex pattern{ R"((.*) = \((.*), (.*)\))" };
for ( string line; getline(input, line); ) {
if ( line.empty() ) {
continue;
}
smatch sub_match;
if ( regex_search(line, sub_match, pattern) ) {
puzzle[sub_match[1]] = { sub_match[2], sub_match[3] };
}
}
auto value = 1L;
for ( const auto& entry: puzzle ) {
if ( entry.first[2] != 'A' ) {
continue;
}
Generator generator{ firstline };
auto counter = 0L;
for ( string str{ entry.first }; str[2] != 'Z'; str = puzzle[str][generator.next()] ) {
++counter;
}
value = lcm(value, counter);
}
cout << value << endl;
}
int
main()
{
part1();
part2();
}
|