From 182e3db84cd4098a9c3e744b8c3159685c523e50 Mon Sep 17 00:00:00 2001 From: Somyagarg0309 <120239080+Somyagarg0309@users.noreply.github.com> Date: Sat, 5 Oct 2024 23:11:20 +0530 Subject: [PATCH] Create RayCasting.java The Ray Casting algorithm, is used to determine whether a point lies inside a polygon. --- .../thealgorithms/geometry/RayCasting.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/main/java/com/thealgorithms/geometry/RayCasting.java diff --git a/src/main/java/com/thealgorithms/geometry/RayCasting.java b/src/main/java/com/thealgorithms/geometry/RayCasting.java new file mode 100644 index 000000000000..82e1dd75dbba --- /dev/null +++ b/src/main/java/com/thealgorithms/geometry/RayCasting.java @@ -0,0 +1,63 @@ +package com.thealgorithms.geometry; + +import java.util.ArrayList; +import java.util.List; + +/** + * A Java program that determines whether a point is inside a polygon using the Ray Casting algorithm. + * The time complexity is O(n), where n is the number of vertices in the polygon. + * The space complexity is O(1). + * + * References: + * https://en.wikipedia.org/wiki/Point_in_polygon + */ +public class RayCasting { + + /** + * Determines if the given point is inside the polygon. + * + * @param polygon An array of points representing the vertices of the polygon. + * @param point The point to check. + * @return true if the point is inside the polygon, false otherwise. + */ + public static boolean isPointInPolygon(Point[] polygon, Point point) { + int n = polygon.length; + boolean inside = false; + + for (int i = 0, j = n - 1; i < n; j = i++) { + if ((polygon[i].y > point.y) != (polygon[j].y > point.y) && + (point.x < (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) / + (polygon[j].y - polygon[i].y) + polygon[i].x)) { + inside = !inside; + } + } + return inside; + } + + /** + * A record representing a point in 2D space. + */ + public record Point(int x, int y) { + /** + * @return A string representation of this point in the format (x, y) + */ + @Override + public String toString() { + return String.format("(%d, %d)", x, y); + } + } + + public static void main(String[] args) { + Point[] polygon = { + new Point(0, 0), + new Point(5, 0), + new Point(5, 5), + new Point(0, 5) + }; + Point testPoint = new Point(3, 3); + System.out.println("Is point " + testPoint + " inside the polygon? " + isPointInPolygon(polygon, testPoint)); // true + + Point outsidePoint = new Point(6, 3); + System.out.println("Is point " + outsidePoint + " inside the polygon? " + isPointInPolygon(polygon, outsidePoint)); // false + } +}