Determine if two rectangles overlap each other?

前端 未结 23 861
礼貌的吻别
礼貌的吻别 2020-11-22 04:09

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectang

23条回答
  •  逝去的感伤
    2020-11-22 04:55

    In the question, you link to the maths for when rectangles are at arbitrary angles of rotation. If I understand the bit about angles in the question however, I interpret that all rectangles are perpendicular to one another.

    A general knowing the area of overlap formula is:

    Using the example:

       1   2   3   4   5   6
    
    1  +---+---+
       |       |   
    2  +   A   +---+---+
       |       | B     |
    3  +       +   +---+---+
       |       |   |   |   |
    4  +---+---+---+---+   +
                   |       |
    5              +   C   +
                   |       |
    6              +---+---+
    

    1) collect all the x coordinates (both left and right) into a list, then sort it and remove duplicates

    1 3 4 5 6

    2) collect all the y coordinates (both top and bottom) into a list, then sort it and remove duplicates

    1 2 3 4 6

    3) create a 2D array by number of gaps between the unique x coordinates * number of gaps between the unique y coordinates.

    4 * 4

    4) paint all the rectangles into this grid, incrementing the count of each cell it occurs over:

       1   3   4   5   6
    
    1  +---+
       | 1 | 0   0   0
    2  +---+---+---+
       | 1 | 1 | 1 | 0
    3  +---+---+---+---+
       | 1 | 1 | 2 | 1 |
    4  +---+---+---+---+
         0   0 | 1 | 1 |
    6          +---+---+
    

    5) As you paint the rectangles, its easy to intercept the overlaps.

提交回复
热议问题