Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the overlap distance of two 1D line segments

Tags:

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?

like image 937
Tonis F. Piip Avatar asked May 22 '13 12:05

Tonis F. Piip


2 Answers

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
like image 192
jamylak Avatar answered Sep 21 '22 00:09

jamylak


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
like image 45
Brad Avatar answered Sep 19 '22 00:09

Brad