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
123
124
125
126
127
128
129
130
131
132
|
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
string
read_file(string_view filename)
{
fstream input{ filename };
return { istreambuf_iterator<char>{ input }, istreambuf_iterator<char>{} };
}
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)) != std::string::npos ) {
auto token = line.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delimiter.length();
res.emplace_back(token);
}
res.emplace_back(line.substr(pos_start));
return res;
}
vector<string>
transpose(const vector<string>& input)
{
vector<string> result(input[0].size());
for ( const auto& i: input ) {
for ( size_t j = 0; j < i.size(); j++ ) {
result[j] += i[j];
}
}
return result;
}
long
find_mirror(const vector<string>& input)
{
for ( size_t idx = 1; idx < input.size(); ++idx ) {
bool equal = true;
for ( size_t cnt = 0; cnt != min(idx, input.size() - idx); ++cnt ) {
auto cmp_result = (input.at(idx + cnt) == input.at(idx - 1 - cnt));
if ( !cmp_result ) {
equal = false;
break;
}
}
if ( equal ) {
return long(idx);
}
}
return 0;
}
void
part1()
{
auto contents = read_file("data/day13.txt");
auto parts = split(contents, "\n\n");
long sum = 0;
for ( const auto& part: parts ) {
auto lines = split(part, "\n");
sum += find_mirror(transpose(lines));
sum += find_mirror(lines) * 100;
}
cout << sum << endl;
}
long
count_differences(string_view a, string_view b) // NOLINT
{
long errs = 0;
for (size_t idx = 0; idx != a.size(); ++idx) {
if (a[idx] != b[idx]) {
++errs;
}
}
return errs;
}
long
find_mirror2(const vector<string>& input)
{
for ( size_t idx = 1; idx < input.size(); ++idx ) {
long errs = 0;
for ( size_t cnt = 0; cnt != min(idx, input.size() - idx); ++cnt ) {
errs += count_differences(input.at(idx + cnt), input.at(idx - 1 - cnt));
}
if ( errs == 1 ) {
return long(idx);
}
}
return 0;
}
void
part2()
{
auto contents = read_file("data/day13.txt");
auto parts = split(contents, "\n\n");
long sum = 0;
for ( const auto& part: parts ) {
auto lines = split(part, "\n");
sum += find_mirror2(transpose(lines));
sum += find_mirror2(lines) * 100;
}
cout << sum << endl;
}
int
main()
{
// part1();
part2();
}
|