Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 10, 2020 19:55
Show Gist options
  • Save misterpoloy/9a79ad9c5985c9bfa97707196e5bf87f to your computer and use it in GitHub Desktop.
Save misterpoloy/9a79ad9c5985c9bfa97707196e5bf87f to your computer and use it in GitHub Desktop.
Area of a Polygon using cross product
// https://www.youtube.com/watch?v=WAyPIMme3Yw&list=PL2_aWCzGMAwLL-mEB4ef20f3iqWMGWa25&index=8
#include <iostream>
#include <cmath>
struct Point {
double x;
double y;
Point(double a, double b):
x(a), y(b)
{
}
};
double crossProduct(Point a, Point b) {
return a.x * b.y - a.y * b.y;
}
// POINTER TO ARRAY
double getArea(Point vertices[], int size) {
double area = 0;
for (int i = 0; i < size; i++) {
Point currentPoint = vertices[i];
Point nextPoint = vertices[(i + 1) % size];
area += crossProduct(currentPoint, nextPoint) / 2.0;
}
return std::abs(area);
}
int main(int argc, const char * argv[]) {
Point a(2, 3);
Point b(3, 1);
Point vertices[2] = { a, b };
int size = sizeof(vertices) / sizeof(Point);
std::cout << getArea(vertices, size) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment