blob: 7765b3fdf8bf10f2c8e8618398b1f490317fcf6e (
plain) (
blame)
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using Dish = std::vector<std::string>;
using History = std::vector<std::vector<bool>>;
constexpr int CYCLES = 1'000'000'000;
Dish parse(const char* file)
{
Dish v;
if (std::ifstream input{ file }; input.is_open())
{
std::string line;
while (not std::getline(input,line).eof())
{
v.push_back(std::move(line));
}
}
return v;
}
std::vector<bool> encode(const Dish& v)
{
auto len = v.size();
std::vector<bool> e(len * len, 0);
for (int x = 0; x < len; ++x)
{
for (int y = 0; y < len; ++y)
{
e[x * len + y] = v[x][y] == 'O';
}
}
return e;
}
Dish& tilt_north(Dish& v)
{
for (int c = 0; c < v.size(); ++c)
{
int floor{};
for (int r = floor; r < v.size(); ++r)
{
switch (v[r][c])
{
case '#':
floor = r + 1;
break;
case 'O':
v[r][c] = '.';
v[floor++][c] = 'O';
}
}
}
return v;
}
Dish& tilt_south(Dish& v)
{
for (int c = 0; c < v.size(); ++c)
{
int floor{ static_cast<int>(v.size() - 1) };
for (int r = floor; r >= 0; --r)
{
switch (v[r][c])
{
case '#':
floor = r - 1;
break;
case 'O':
v[r][c] = '.';
v[floor--][c] = 'O';
}
}
}
return v;
}
Dish& tilt_west(Dish& v)
{
for (int r = 0; r < v.size(); ++r)
{
int floor{};
for (int c = floor; c < v.size(); ++c)
{
switch (v[r][c])
{
case '#':
floor = c + 1;
break;
case 'O':
v[r][c] = '.';
v[r][floor++] = 'O';
}
}
}
return v;
}
Dish& tilt_east(Dish& v)
{
for (int r = 0; r < v.size(); ++r)
{
int floor{ static_cast<int>(v.size() - 1) };
for (int c = floor; c >= 0; --c)
{
switch (v[r][c])
{
case '#':
floor = c - 1;
break;
case 'O':
v[r][c] = '.';
v[r][floor--] = 'O';
}
}
}
return v;
}
Dish& cycle(Dish& v)
{
return tilt_east(tilt_south(tilt_west(tilt_north(v))));
}
int load(const std::vector<bool>& v, int l)
{
int load{};
for (int x = 0; x < l; ++x)
{
for (int y = 0; y < l; ++y)
{
load += (l - x) * v[x * l + y];
}
}
return load;
}
int dup(History& hist, Dish dish)
{
auto h = encode(dish);
if (auto found = std::find(hist.cbegin(), hist.cend(), h); found != hist.cend())
{
return hist.cend() - found;
}
hist.push_back(std::move(h));
return 0;
}
int main(int argc, char* argv[])
{
auto v = parse(argv[1]);
History history;
history.push_back(encode(v));
int p, np;
for (p = 0; p == 0; p = dup(history, cycle(v)));
np = history.size() - p;
std::cout << load(history[np + (CYCLES - np) % p], v.size()) << std::endl;
return 0;
}
|