/// <summary> /// Returns the convex hull of the points created from the list /// <code>points</code>. Note that the first and last point in the /// returned <code>List<java.awt.Point></code> are the same /// point. /// </summary> /// <param name="points">The list of points. </param> /// <returns>The convex hull of the points created from the list <code>points</code>. </returns> public static IList <IntPoint> GetConvexHull(List <IntPoint> points) { IntPoint lowestPoint = GetLowestPoint(points); // Sort points based on angle to lowestPoint IntPointSorter sorter = new IntPointSorter(lowestPoint); points.Sort(sorter.ComparePoints); // Alias for clarity List <IntPoint> sorted = points; if (sorted.Count < 3) { throw new System.ArgumentException("can only create a convex hull of 3 or more unique points"); } if (AreAllCollinear(sorted)) { throw new System.ArgumentException("cannot create a convex hull from collinear points"); } Stack <IntPoint> stack = new Stack <IntPoint>(); stack.Push(sorted[0]); stack.Push(sorted[1]); for (int i = 2; i < sorted.Count; i++) { IntPoint head = sorted[i]; IntPoint middle = stack.Pop(); IntPoint tail = stack.Peek(); Turn turn = GetTurn(tail, middle, head); switch (turn) { case Turn.CounterClockwise: stack.Push(middle); stack.Push(head); break; case Turn.Clockwise: i--; break; case Turn.Collinear: stack.Push(head); break; } } // close the hull stack.Push(sorted[0]); return(new List <IntPoint>(stack)); }
/// <summary> /// Returns the convex hull of the points created from the list /// <code>points</code>. Note that the first and last point in the /// returned <code>List<java.awt.Point></code> are the same /// point. /// </summary> /// <param name="points">The list of points. </param> /// <returns>The convex hull of the points created from the list <code>points</code>. </returns> public static IList<IntPoint> GetConvexHull(List<IntPoint> points) { IntPoint lowestPoint = GetLowestPoint(points); // Sort points based on angle to lowestPoint IntPointSorter sorter = new IntPointSorter(lowestPoint); points.Sort(sorter.ComparePoints); // Alias for clarity List<IntPoint> sorted = points; if (sorted.Count < 3) { throw new System.ArgumentException("can only create a convex hull of 3 or more unique points"); } if (AreAllCollinear(sorted)) { throw new System.ArgumentException("cannot create a convex hull from collinear points"); } Stack<IntPoint> stack = new Stack<IntPoint>(); stack.Push(sorted[0]); stack.Push(sorted[1]); for (int i = 2; i < sorted.Count; i++) { IntPoint head = sorted[i]; IntPoint middle = stack.Pop(); IntPoint tail = stack.Peek(); Turn turn = GetTurn(tail, middle, head); switch (turn) { case Turn.CounterClockwise: stack.Push(middle); stack.Push(head); break; case Turn.Clockwise: i--; break; case Turn.Collinear: stack.Push(head); break; } } // close the hull stack.Push(sorted[0]); return new List<IntPoint>(stack); }