From 13086785736a2a4886f687ea6664fa1f782a58d9 Mon Sep 17 00:00:00 2001 From: dyrpsf Date: Mon, 13 Oct 2025 15:37:09 +0530 Subject: [PATCH 1/2] docs: add JavaDoc to AreaOfPolygon algorithm --- .../thealgorithms/maths/AreaOfPolygon.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/main/java/com/thealgorithms/maths/AreaOfPolygon.java diff --git a/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java b/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java new file mode 100644 index 000000000000..167556d22805 --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java @@ -0,0 +1,40 @@ +/** + * This class provides a method to calculate the area of a simple polygon + * using the Shoelace formula (Gauss's area formula). + * + * The vertices should be ordered either clockwise or counter-clockwise. + */ +public class AreaOfPolygon { + + /** + * Calculates the area of a polygon using x and y coordinates. + * Uses the Shoelace formula: + * Area = (1/2) * |x[i]*y[i+1] - x[i+1]*y[i]| + * + * @param x x-coordinates of the polygon's vertices + * @param y y-coordinates of the polygon's vertices + * @return area of the polygon + * @throws IllegalArgumentException if x and y are different lengths + */ + public static double area(double[] x, double[] y) { + if (x.length != y.length) { + throw new IllegalArgumentException("Arrays must be same length"); + } + + double sum = 0.0; + int n = x.length; + + for (int i = 0; i < n; i++) { + sum += (x[i] * y[(i + 1) % n]) - (x[(i + 1) % n] * y[i]); + } + + return Math.abs(sum) / 2.0; + } + + // Sample usage + public static void main(String[] args) { + double[] x = {0, 4, 4, 0}; + double[] y = {0, 0, 4, 4}; + System.out.println("Area: " + area(x, y)); // Should print 16.0 + } +} \ No newline at end of file From b1064adc3dfe65c212cce5a7c8afe6ed347c98d7 Mon Sep 17 00:00:00 2001 From: dyrpsf Date: Mon, 13 Oct 2025 16:01:45 +0530 Subject: [PATCH 2/2] style: fix formatting using clang-format --- src/main/java/com/thealgorithms/maths/AreaOfPolygon.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java b/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java index 167556d22805..f806e9c034d2 100644 --- a/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java +++ b/src/main/java/com/thealgorithms/maths/AreaOfPolygon.java @@ -37,4 +37,4 @@ public static void main(String[] args) { double[] y = {0, 0, 4, 4}; System.out.println("Area: " + area(x, y)); // Should print 16.0 } -} \ No newline at end of file +}