Find overlap between collinear lines
Asked Answered
T

2

14

Given two collinear line segments AB and CD, how do I find if they overlap? How do I locate the start and end points of the overlap?

Below is the approach I am using. I am first ensuring that A < B and C < D.

if(pa < pc){
  if(pc < pb){
    if(pd < pb){
      //  overlap exists; CD falls entirely within AB
    }
    else {
      //  overlap exists; CB is the overlapping segment
    }
  }
  else {
    //  no overlap exists; AB lies before CD
  }
}
else {
  if(pa < pd){
    if(pb < pd){
      //  overlap exists; AB lies entirely within CD
    }
    else {
      //  overlap exists; AD is the overlapping segment
    }
  }
  else {
    //  no overlap exists; CD lies before AB
  }
}

Now, isn't there a simpler solution to do this?

Update:there is another way... compare the sum of the lengths of both segments with the distance between the outermost points. If the latter is the lesser, overlap exists.

Thunderstorm answered 31/3, 2013 at 5:59 Comment(0)
H
24

Ensure A<B, C<D:

if (pb - pc >= 0 and pd - pa >=0 ) { // overlap
    OverlapInterval = [ max(pa, pc), min(pb, pd) ] // it could be a point [x, x]
} // else: not overlap
Hear answered 4/4, 2013 at 13:28 Comment(1)
Brilliant! Welcome to SO!!Thunderstorm
D
5

Ensure A<B, C<D, and A<=C (which you can do by simple swapping). Then:

  • if B<C, the segments are disjoint
  • if B=C, then the intersection is the single point B=C
  • if B>C, then the intersection is the segment [C, min(B, D)]
Dink answered 31/3, 2013 at 6:10 Comment(2)
Whqat do you mean with A < B? by means of A.x and B.x? for equal x who can you ensure that?Logogram
A,B is the first segment, C,D is the second segment.Gaudery

© 2022 - 2024 — McMap. All rights reserved.