Merge two segments on the same circle if they intersect or intersect

I am trying to merge two segments if they overlap or intersect. My question is similar to this and this . However, I want to combine the two segments.

public class Segment
{
    private readonly double _from;
    private readonly double _to;
    public Segment(double from, double to)
    {
        _from = Normalize(from); // 0 <= x < 360
        _to = Normalize(to);
    }

    public bool Inside(double target)
    {
        if (_from < _to)
            return _from <= target && target <= _to;
        return _from <= target || target <= _to;
    }
}

I'm trying to write TryCombine().

public bool TryCombine(Segment other, out Segment result)
{
    // if not intersect
    // return false

    // else if overlap
    // return true, out larger one

    // else if intersect
    // return true, out a new one with merged bound
}

Expected Result

var seg1 = new Segment(0, 100);
var seg2 = new Segment(50, 150);
var seg3 = new Segment(110, -100);
var seg4 = new Segment(10, 50);
Segment result;

seg1.TryCombine(seg2, result); // True, result = Segment(0, 150)
seg1.TryCombine(seg3, result); // False
seg1.TryCombine(seg4, result); // True, result = Segment(0, 100)
seg2.TryCombine(seg3, result); // True, result = Segment(260, 150)
0
source share
1 answer

You can use the approach described in my answer in your second link.

ma = (a2 + a1)/ 2  
mb = (b2 + b1)/ 2  
cda = Cos(da)
cdb = Cos(db)

To check if an intersection exists and what kind of intersection occurs, find 4 Boolean values

 BStartInsideA = (Cos(ma - b1) >= cda)
 BEndInsideA  =  (Cos(ma - b2) >= cda)
 AStartInsideB = (Cos(mb - a1) >= cdb)
 AEndInsideB =   (Cos(mb - a2) >= cdb)

16 ( ). 4- case.

, ( 0b1001 = 9), , seg1-seg2 - AStart , BEnd ( 360 BEnd, AStart).

BEnd >= BStart AEnd >= AStart (, (3,1) (3, 361) 182 179)

( , 4 , 4 ):

 0000: no intersection
 1111: full circle

 0011: AStart-AEnd
 1001: AStart-BEnd
 0110: BStart-AEnd
 1100: BStart-BEnd

 0111: AStart-AEnd
 1011: AStart-AEnd
 1110: BStart-BEnd
 1101: BStart-BEnd

1010, 0101

, :

 At first check for 
   0000: no intersection
   1111: full circle
 then
   **11: AStart-AEnd
   1001: AStart-BEnd
   0110: BStart-AEnd
   11**: BStart-BEnd
+1

Source: https://habr.com/ru/post/1668737/


All Articles