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
|
#pragma once
#include "common.h"
#include <math.h>
namespace aoc2019 {
struct belt {
static constexpr int grid = 34;
struct distance {
int dx;
int dy;
};
struct pos {
int x;
int y;
friend bool operator==(const pos &p1, const pos &p2) {
return p1.x == p2.x && p1.y == p2.y;
}
};
char map[grid * grid] = {0};
belt(const belt& b) {
memcpy(map, b.map, grid * grid);
}
belt& operator=(const belt& b) {
if (this != &b) {
memcpy(map, b.map, grid * grid);
}
return *this;
}
belt() {}
char& get(int x, int y) {
return map[y * grid + x];
}
char& get(pos p) {
return get(p.x, p.y);
}
void load(line_view lv, int row) {
const char* p = lv.line;
for (int i = 0; i < grid; i++) {
get(i, row) = *(p + i);
}
}
distance diff(pos px, pos p) const noexcept {
auto d = distance{px.x - p.x, px.y - p.y};
int g = gcd(std::abs(d.dx), std::abs(d.dy));
return distance {d.dx / g, d.dy / g};
}
distance dist(pos px, pos p) const noexcept {
return distance{px.x - p.x, px.y - p.y};
}
bool valid (pos p) const noexcept {
return p.x >= 0 && p.x < grid && p.y >= 0 && p.y < grid;
}
pos next(pos p, distance d) const noexcept {
return pos{p.x + d.dx, p.y + d.dy};
}
bool blocked(pos p, pos m) {
auto d = diff(p, m);
auto n = next(m, d);
while (valid(n) && !(n == p)) {
if (get(n) == '#') {
return true;
}
n = next(n, d);
}
return false;
}
template<typename F, typename... Args>
void iterate(F&& f, Args&&... args) {
for(int y = 0; y < grid; y++) {
for (int x = 0; x < grid; x++) {
f(pos{x, y}, std::forward(args)...);
}
}
}
void print() {
iterate([this](pos p){
printf("%c", get(p));
if (p.x == grid - 1) {
printf("\n");
}
});
printf("\n");
}
void count(pos m, int* c) {
iterate([this, &m, &c](pos p){
if (get(p) == '#' && !(p == m)) {
if (!blocked(p, m)) {
*c += 1;
}
}
});
}
};
std::pair<int, int> day10(line_view);
}
|