23

Trying to build a function that will return the total overlapping distance between 2 line segments, denoted by start and end ints.

Currently I have this: That I got off the internet somewhere,

def overlap(min1, max1, min2, max2):
    """returns the overlap between two lines that are 1D"""
    result = None
    if min1 >= max2 or min2 >= max1: result =  0
    elif min1 <= min2:
        result = max1 - min2
    else: result = max2 - min1
    return result

This works however for the case of 0 100, 0,20 it returns 100. And that's clearly wrong. Is there a simple way of calculating this that will return the correct values?

RedBaron
  • 4,717
  • 5
  • 41
  • 65
Tonis F. Piip
  • 776
  • 2
  • 6
  • 16

3 Answers3

58
def overlap(min1, max1, min2, max2):
    return max(0, min(max1, max2) - max(min1, min2))

>>> overlap(0, 10, 80, 90)
0
>>> overlap(0, 50, 40, 90)
10
>>> overlap(0, 50, 40, 45)
5
>>> overlap(0, 100, 0, 20)
20
jamylak
  • 128,818
  • 30
  • 231
  • 230
6

Not fully tested, but how about -

def overlap(min1,max1,min2,max2):
    start = max(min1,min2)
    end = min(max1,max2)
    d = end - start
    if d < 0:
        return 0
    else:
        return d

#some tests
print overlap(0,100,0,20)
print overlap(5,10,15,20)
print overlap(1,3,0,5)
print overlap(-5,5,-2,10)

>>> 
20
0
2
7
Brad
  • 1,367
  • 1
  • 8
  • 17
1

In 1-D the premise of checking for overlaps is simple (I think). Find the bigger of the minimum values and the smaller of the maximum values. Then subtract the two.

def overlap(min1, max1, min2, max2):
    #Find out the bigger minimum
    if min1 >= min2: 
        bigger_min = min1
    else: 
        bigger_min = min2
    if max1 >= max2: 
        smaller_max = max2
    else: 
        smaller_max = max1
    if smaller_max <= bigger_min: 
        return 0
    else: 
        return smaller_max - bigger_min

Results

>>> overlap(20,40,30,70)
10
>>> overlap(0,100,200,300)
0
>>> overlap(0,100,0,30)
30
>>> overlap(0,100,30,60)
30
>>> overlap(0,100,30,70)
40
>>> overlap(20,100,30,70)
40
>>> overlap(20,30,30,70)
0
>>> overlap(0,50,0,50)
50
RedBaron
  • 4,717
  • 5
  • 41
  • 65