Intersection Area

Intersection Area

December 12, 2023
easy

Problem #

Given two rectangles on a 2D graph, return the area of their intersection. If the rectangles don’t intersect, return 0.

For example, given the following rectangles:

{
    "top_left": (1, 4),
    "dimensions": (3, 3) # width, height
}

and

{
    "top_left": (0, 5),
    "dimensions": (4, 3) # width, height
}

return 6.

solution #

def calculate_intersection_area(rect1, rect2):
    """
    Calculate the area of intersection of two rectangles.
    Each rectangle is represented as a dictionary with 'top_left' and 'dimensions' keys.
    'top_left' is a tuple (x, y) representing the top left coordinate of the rectangle.
    'dimensions' is a tuple (width, height) of the rectangle.
    """
    
    # Extract coordinates and dimensions of the first rectangle
    x1, y1 = rect1['top_left']
    w1, h1 = rect1['dimensions']
    
    # Calculate bottom right coordinates of the first rectangle
    x1_br = x1 + w1
    y1_br = y1 - h1

    # Extract coordinates and dimensions of the second rectangle
    x2, y2 = rect2['top_left']
    w2, h2 = rect2['dimensions']
    
    # Calculate bottom right coordinates of the second rectangle
    x2_br = x2 + w2
    y2_br = y2 - h2

    # Calculate the overlap coordinates
    overlap_left = max(x1, x2)
    overlap_right = min(x1_br, x2_br)
    overlap_top = min(y1, y2)
    overlap_bottom = max(y1_br, y2_br)

    # Check if there is an overlap
    if overlap_left < overlap_right and overlap_bottom < overlap_top:
        overlap_width = overlap_right - overlap_left
        overlap_height = overlap_top - overlap_bottom
        return overlap_width * overlap_height
    else:
        return 0

# Test the function with the given rectangles
rect1 = {"top_left": (1, 4), "dimensions": (3, 3)} # width, height
rect2 = {"top_left": (0, 5), "dimensions": (4, 3)} # width, height

area = calculate_intersection_area(rect1, rect2)
print(f"The area of intersection is: {area}")

This code defines a function calculate_intersection_area that takes two rectangles as input and calculates the area of their intersection. If the rectangles don’t intersect, it returns 0. For the provided example, it will output the intersection area as 6.