Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created June 27, 2024 07:36
Show Gist options
  • Save chuongmep/e3ef552c80bf19b6ff405e2e7e0b2b54 to your computer and use it in GitHub Desktop.
Save chuongmep/e3ef552c80bf19b6ff405e2e7e0b2b54 to your computer and use it in GitHub Desktop.
public static List<XYZ> ComputeConvexHull(List<XYZ> points)
{
if (points == null || points.Count < 3)
throw new ArgumentException("At least 3 points are required to compute a convex hull");
List<XYZ> hull = new List<XYZ>();
// Find the leftmost point
XYZ leftmost = points[0];
foreach (var point in points)
{
if (point.X < leftmost.X)
{
leftmost = point;
}
}
XYZ currentPoint = leftmost;
do
{
hull.Add(currentPoint);
XYZ nextPoint = points[0];
foreach (var point in points)
{
if (nextPoint == currentPoint || IsLeftTurn(currentPoint, nextPoint, point))
{
nextPoint = point;
}
}
currentPoint = nextPoint;
} while (currentPoint != leftmost);
return hull;
}
private static bool IsLeftTurn(XYZ a, XYZ b, XYZ c)
{
return ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)) > 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment