File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
src/main/java/com/thealgorithms/maths Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments