Linear expression for intersection length of two lines in 1D

305 Views Asked by At

Given the first line from a to b where a < b and the second line from x to y where x < y, how do you calculate the intersection length of those two?

Example:

a =0, b=5, x=3, y=7

012345
|----|
   |---|
   34567

the result would be 2 since they are intersection from 3 to 5.

Is there an expression with these 4 variables to extract the result? There is no guarantee that there is an intersection nor is it guaranteed that x > a

I have looked at timespan intersection examples but they all have an if expression in them which is not possible in my situation.

1

There are 1 best solutions below

4
On

Logic is quite simple:

if (y<a) or (x>b):
       return  no intersection

intersection.left = max(a, x)
intersectioni.right = min(b, y)