lucasmcdonald3
9/28/2018 - 4:44 PM

Fraction Rectangles Overlap

# returns % of overlap of rectangles
# rect = (startX, startY, endX, endY)
def fraction_bounds_overlap(rect1, rect2):
    rect1_area = max(0, rect1[2] - rect1[0]) * max(0, rect1[3] - rect1[1])
    rect2_area = max(0, rect2[2] - rect2[0]) * max(0, rect2[3] - rect2[1])
    intersection = (max(0, min(rect1[2], rect2[2]) - max(rect1[0], rect2[0]))
                  * max(0, min(rect1[3], rect2[3]) - max(rect1[1], rect2[1])))
    if min(rect1_area, rect2_area) != 0:
        return intersection / min(rect1_area, rect2_area)
    else:
        return 0