public static Poly ConvexHull(Poly poly) { Array.Sort(poly.point); Point adj = new Point(poly.point[0].x, poly.point[0].y); for (int i = 0; i < poly.point.Length; i++) { poly.point[i] -= adj; } Array.Sort(poly.point, new PolarPointComparer()); // Vector sort ArrayList hull = new ArrayList(); for (int i = 0; i < poly.point.Length; i++) { Point cur = poly.point[i] + adj; if (hull.Count > 0 && hull[hull.Count - 1].Equals(cur)) { continue; } while (hull.Count > 1 && Point.Cross((Point)hull[hull.Count - 2], (Point)hull[hull.Count - 1], cur) >= 0) { hull.RemoveAt(hull.Count - 1); } hull.Add(cur); } return(new Poly((Point[])hull.ToArray(typeof(Point)))); }
public void TestConvexHull2() { string input = "1,2 4,1 6,1 5,3 3,3 7,3 8,4 6,5 4,5 2,5 3,7 5,6"; string expected = "1,2 2,5 3,7 5,6 8,4 6,1 4,1"; var inputPoly = input.Split(' ').Select(x => new Point(x[0] - '0', x[2] - '0')).ToArray(); var expectedPoly = expected.Split(' ').Select(x => new Point(x[0] - '0', x[2] - '0')).ToArray(); var actual = Poly.ConvexHull(new Poly(inputPoly.ToArray())); Assert.AreEqual(expectedPoly.Length, actual.point.Length); for (int i = 0; i < actual.point.Length; i++) { Assert.AreEqual(expectedPoly[i], actual.point[i]); } }
public void TestConvexHull1() { List <Point> al = new List <Point>(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { al.Add(new Point(i, j)); } } Poly p = Poly.ConvexHull(new Poly(al.ToArray())); Assert.AreEqual(4, p.point.Length); }