Skip to content

Commit 1308678

Browse files
committed
docs: add JavaDoc to AreaOfPolygon algorithm
1 parent f30d101 commit 1308678

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* This class provides a method to calculate the area of a simple polygon
3+
* using the Shoelace formula (Gauss's area formula).
4+
*
5+
* The vertices should be ordered either clockwise or counter-clockwise.
6+
*/
7+
public class AreaOfPolygon {
8+
9+
/**
10+
* Calculates the area of a polygon using x and y coordinates.
11+
* Uses the Shoelace formula:
12+
* Area = (1/2) * |x[i]*y[i+1] - x[i+1]*y[i]|
13+
*
14+
* @param x x-coordinates of the polygon's vertices
15+
* @param y y-coordinates of the polygon's vertices
16+
* @return area of the polygon
17+
* @throws IllegalArgumentException if x and y are different lengths
18+
*/
19+
public static double area(double[] x, double[] y) {
20+
if (x.length != y.length) {
21+
throw new IllegalArgumentException("Arrays must be same length");
22+
}
23+
24+
double sum = 0.0;
25+
int n = x.length;
26+
27+
for (int i = 0; i < n; i++) {
28+
sum += (x[i] * y[(i + 1) % n]) - (x[(i + 1) % n] * y[i]);
29+
}
30+
31+
return Math.abs(sum) / 2.0;
32+
}
33+
34+
// Sample usage
35+
public static void main(String[] args) {
36+
double[] x = {0, 4, 4, 0};
37+
double[] y = {0, 0, 4, 4};
38+
System.out.println("Area: " + area(x, y)); // Should print 16.0
39+
}
40+
}

0 commit comments

Comments
 (0)