Skip to content

Instantly share code, notes, and snippets.

@mateusfccp
Created August 18, 2020 17:45
Show Gist options
  • Save mateusfccp/b6a8f5b15ab63a269b3bb6c147d60fdb to your computer and use it in GitHub Desktop.
Save mateusfccp/b6a8f5b15ab63a269b3bb6c147d60fdb to your computer and use it in GitHub Desktop.
Centroid
import 'dart:math';
num add(num a, num b) => a + b;
num sumPoints(
List<Point> points,
num Function(num) generator,
) =>
List.generate(
points.length,
generator,
).reduce(add);
num Function(int i) commonPart(List<Point> points) => (int i) =>
points[i].x * points[(i + 1) % points.length].y -
points[(i + 1) % points.length].x * points[i].y;
num internalArea(List<Point> points) => sumPoints(
points,
commonPart(points),
);
num xPart(List<Point> points) => sumPoints(
points,
(i) =>
(points[i].x + points[(i + 1) % points.length].x) *
commonPart(points)(i),
);
num yPart(List<Point> points) => sumPoints(
points,
(i) =>
(points[i].y + points[(i + 1) % points.length].y) *
commonPart(points)(i),
);
double signedArea(List<Point> points) => (internalArea(points) / 2);
double centroidX(List<Point> points) =>
xPart(points) / (6 * signedArea(points));
double centroidY(List<Point> points) =>
yPart(points) / (6 * signedArea(points));
Point centroid(List<Point> points) => Point(
centroidX(points),
centroidY(points),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment