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
|
#include <filesystem>
#include <fstream>
#include <iostream>
#include <regex>
#include <set>
#include <tuple>
#include <vector>
using namespace std;
namespace {
struct Point {
long x;
long y;
long vx;
long vy;
};
vector<Point>
read_file(const filesystem::path& filename)
{
ifstream file{ filename };
static const regex pattern{ R"(position=<\s*(-?\d+)\s*,\s*(-?\d+)\s*>\s*velocity=<\s*(-?\d+)\s*,\s*(-?\d+)\s*>)" };
vector<Point> data;
for ( string line; getline(file, line); ) {
smatch match;
if ( regex_match(line, match, pattern) ) {
auto x = stol(match[1]);
auto y = stol(match[2]);
auto vx = stol(match[3]);
auto vy = stol(match[4]);
data.emplace_back(x, y, vx, vy);
}
}
return data;
}
void
get_bounding_box(const vector<Point>& points, long& min_x, long& min_y, long& max_x, long& max_y)
{
min_x = numeric_limits<long>::max();
min_y = numeric_limits<long>::max();
max_x = numeric_limits<long>::min();
max_y = numeric_limits<long>::min();
for ( const auto& point: points ) {
min_x = min(min_x, point.x);
min_y = min(min_y, point.y);
max_x = max(max_x, point.x);
max_y = max(max_y, point.y);
}
}
long
bounding_area(const vector<Point>& points)
{
long min_x = 0;
long min_y = 0;
long max_x = 0;
long max_y = 0;
get_bounding_box(points, min_x, min_y, max_x, max_y);
return 1L * (max_x - min_x + 1) * (max_y - min_y + 1);
}
void
update(vector<Point>& points)
{
for ( auto& point: points ) {
point.x += point.vx;
point.y += point.vy;
}
}
tuple<int, vector<Point>>
get_best(vector<Point> points)
{
auto best_area = numeric_limits<long>::max();
vector<Point> best;
int best_t = 0;
for ( int i = 0; i != 100'000; ++i ) {
update(points);
auto area = bounding_area(points);
if ( area < best_area ) {
best_area = area;
best = points;
best_t = i + 1;
}
}
return { best_t, best };
}
void
print(const vector<Point>& points)
{
set<tuple<long, long>> grid;
for ( const auto [x, y, vx, vy]: points ) {
grid.emplace(x, y);
}
long min_x = 0;
long min_y = 0;
long max_x = 0;
long max_y = 0;
get_bounding_box(points, min_x, min_y, max_x, max_y);
for ( long y = min_y; y <= max_y; ++y ) {
for ( long x = min_x; x <= max_x; ++x ) {
cout << (grid.contains({ x, y }) ? '#' : ' ');
}
cout << '\n';
}
}
void
solve(const vector<Point>& points)
{
auto [time, best_points] = get_best(points);
print(best_points);
cout << "Part 2: " << time << '\n';
}
} // namespace
int
main()
{
auto data = read_file("data/day10.txt");
solve(data);
}
|