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
|
#include "aoc.h"
#include <algorithm>
#include <vector>
namespace aoc2021 {
static void get_number(const char** pp, int* d) {
*d = 0;
const char* p = *pp;
while (*p >= '0' && *p <= '9') {
*d = *d * 10 + *p - '0';
p++;
}
*pp = p;
}
void fill(std::vector<int>& b1, std::vector<int>& b2, const line& l, int width) {
if (l.is_vertical() || l.is_horizontal()) {
l.traverse([&b1, &b2, width](line::point p) {
b1[p.y * width + p.x] += 1;
b2[p.y * width + p.x] += 1;
});
}
if (l.is_diagonal()) {
l.traverse([&b2, width](line::point p) { b2[p.y * width + p.x] += 1; });
}
}
std::pair<int, int> day5(line_view file) {
std::vector<line> vs;
int maxx{INT32_MIN};
int maxy{INT32_MIN};
per_line(file, [&vs, &maxx, &maxy](line_view lv) {
line l;
int* is[] = {&l.p1.x, &l.p1.y, &l.p2.x, &l.p2.y};
const char* p = lv.line;
int i{0};
while (p < lv.line + lv.length) {
if (*p >= '0' && *p <= '9') {
get_number(&p, is[i++]);
}
p++;
}
if (l.p2 < l.p1) {
std::swap(l.p1, l.p2);
}
maxx = std::max(maxx, std::max(l.p1.x, l.p2.x));
maxy = std::max(maxy, std::max(l.p1.y, l.p2.y));
vs.push_back(l);
return true;
});
maxx += 1;
maxy += 1;
// printf("%d, %d\n", maxx, maxy);
std::vector<int> board1(maxx * maxy, 0);
std::vector<int> board2(maxx * maxy, 0);
for (auto& l : vs) {
fill(board1, board2, l, maxx);
}
int t1{0};
int t2{0};
std::for_each(board1.begin(), board1.end(), [&t1](int x) { t1 += int(x >= 2); });
std::for_each(board2.begin(), board2.end(), [&t2](int x) { t2 += int(x >= 2); });
return {t1, t2};
}
} // namespace aoc2021
|