Search code examples
c#sortinggeometryplane

How can I tell if a list of 3 or more line segments form a closed region (in 3D)?


OK, here's what I have so far:

Assumptions: You have at least 3 coplanar line segments

  1. Sort the list by x-coordinate of start point or something

  2. Step through the list and see if the start point of line2 is at the end point of line 1 and so on

  3. If the end point of the last one is on the start point of the first one, then I know it is a closed region

How would I go about implementing that in C-Sharp? Do you think it will even work? If so, what sorting algorithm should I use?


Solution

  • Suppose a line segment is represented as follows.

    class Segment
    {
        public Point A { get; set; }
        public Point B { get; set; }
    }
    
    class Point
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }
    }
    

    Suppose segments is an IEnumerable<Segment> containing 3 line segments. Then you can check if the 3 line segments form a closed triangle as follows.

    bool closed = segments
        .SelectMany(segment => new[] { segment.A, segment.B })
        .GroupBy(point => new { point.X, point.Y, point.Z })
        .All(group => group.Count() == 2);
    

    This doesn't consider the degenerate case of segments for which A and B are the same. You can easily add that in and decide for yourself what you want to do in that case.