|
1 | 1 | // POLYGONS |
| 2 | +// Pick's Theorem |
| 3 | +// polygon without self-intersections & if all vertices have integer coordinates in 2D grid |
| 4 | +// Area = I + B/2 - 1. B = # of points lying on polygon sides == (sum of gcd(x_diff, y_diff) on edges) |
| 5 | +// I = number of points with integer coordinates lying strictly inside the polygon |
2 | 6 |
|
3 | 7 | // Implementation |
4 | 8 | // 3 points, entered in counter clockwise order, 0-based indexing |
@@ -113,38 +117,28 @@ vdd convexHull(vdd P){ |
113 | 117 |
|
114 | 118 |
|
115 | 119 | //for finding the centroid of a polygon |
116 | | -point compute2DPolygonCentroid(const std::vector<point> vertices) { |
117 | | - point centroid; |
118 | | - double signedArea = 0.0; |
119 | | - double x0 = 0.0; // Current vertex X |
120 | | - double y0 = 0.0; // Current vertex Y |
121 | | - double x1 = 0.0; // Next vertex X |
122 | | - double y1 = 0.0; // Next vertex Y |
123 | | - double a = 0.0; // Partial signed area |
124 | | - for (int i = 0; i < vertices.size() - 1; ++i) { |
125 | | - |
126 | | - x0 = vertices[i].x; |
127 | | - y0 = vertices[i].y; |
128 | | - x1 = vertices[i + 1].x; |
129 | | - y1 = vertices[i + 1].y; |
| 120 | +dd compute2DPolygonCentroid(const vdd P) { |
| 121 | + dd centroid; |
| 122 | + double signedArea, x0, y0, x1, y1, a = 0.0; |
| 123 | + for (int i = 0; i < P.size() - 1; ++i) { |
| 124 | + x0, y0 = P[i].first, P[i].second; |
| 125 | + x1, y1 = P[i + 1].first, P[i + 1].second; |
130 | 126 | a = x0 * y1 - x1 * y0; |
131 | 127 | signedArea += a; |
132 | | - centroid.x += (x0 + x1) * a; |
133 | | - centroid.y += (y0 + y1) * a; |
134 | | - |
| 128 | + centroid.first += (x0 + x1) * a; |
| 129 | + centroid.second += (y0 + y1) * a; |
135 | 130 | } |
136 | | - x0 = vertices.back().x; |
137 | | - y0 = vertices.back().y; |
138 | | - x1 = vertices.front().x; |
139 | | - y1 = vertices.front().y; |
| 131 | + |
| 132 | + x0, y0 = P.back().first, P.back().second; |
| 133 | + x1, y1 = P.front().first, P.front().second; |
140 | 134 | a = x0 * y1 - x1 * y0; |
141 | 135 | signedArea += a; |
142 | | - centroid.x += (x0 + x1) * a; |
143 | | - centroid.y += (y0 + y1) * a; |
| 136 | + centroid.first += (x0 + x1) * a; |
| 137 | + centroid.second += (y0 + y1) * a; |
144 | 138 |
|
145 | 139 | signedArea *= 0.5; |
146 | | - centroid.x /= (6.0 * signedArea); |
147 | | - centroid.y /= (6.0 * signedArea); |
| 140 | + centroid.first /= (6.0 * signedArea); |
| 141 | + centroid.second /= (6.0 * signedArea); |
148 | 142 |
|
149 | 143 | return centroid; |
150 | 144 | } |
0 commit comments