Home c++ How to find the area of ​​intersection of two rectangles?

How to find the area of ​​intersection of two rectangles?

Author

Date

Category

There are two side rectangles that are parallel to the axes and they intersect. We know:

(x1, y1) – bottom left point of first rectangle

(x2, y2) – top right point of the first rectangle

(x3, y3) – bottom left point of the second rectangle

(x4, y4) – upper right point of the second rectangle

And you need to find the area of ​​their intersection. But they can intersect from different sides.


Answer 1, authority 100%

Although the question is simple, I’ll leave it as a snippet cheat sheet:

# include & lt; algorithm & gt;
/ *
  x1, y1 - lower left point of the first rectangle
  x2, y2 - upper right point of the first rectangle
  x3, y3 - lower left point of the second rectangle
  x4, y4 - upper right point of the second rectangle
* /
int f (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
  int left = std :: max (x1, x3);
  int top = std :: min (y2, y4);
  int right = std :: min (x2, x4);
  int bottom = std :: max (y1, y3);
  int width = right - left;
  int height = top - bottom;
  if (width & lt; 0 || height & lt; 0)
    return 0;
  return width * height;
}

Based on the question, I believe that the coordinates grow from the lower left corner (if Y grows from top to bottom, then you need to make the appropriate corrections).

The idea is simple, illustrated in the picture (it is shown how the width of the common rectangle is determined, the height is determined in the same way):

Previous articleDoubly linked list
Next articleOkHttp 3 for Beginners

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions