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

(x1, y1) - the left bottom point of the first rectangle

(x2, y2) - the upper right point of the first rectangle

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

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

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

  • Such an experienced participant: ten months on the site, as much as 26 points reputation, and such a question: (. - Igor
  • @Igor I just have a lot of rectangles that I need to touch on with one another. And I can not understand how to find the area of ​​intersection of each with each. How to move them and whether they intersect I know. But I can not understand this. Since ety rectangles can intersect on different sides. If you know, then please help - Oleksii Havryshkiv
  • You can find a common rectangle for both, and then multiply its width by its height. - Vladimir Gamalyan
  • @VladimirGamalyan how to find the intersection we need. - Oleksii Havryshkiv
  • one
    Well, it's simple, с.left = max(a.left, b.left); , с.top = max(a.top, b.top); , c.right = min(a.right, b.right ); , c.bottom = min(a.bottom, b.bottom ); (well, another check that the non-negative dimensions turned out, in case they do not overlap). - Vladimir Gamalyan

1 answer 1

Although the question is simple, I'll leave it as a snippet crib:

 #include <algorithm> /* x1, y1 - левая нижняя точка первого прямоугольника x2, y2 - правая верхняя точка первого прямоугольника x3, y3 - левая нижняя точка второго прямоугольника x4, y4 - правая верхняя точка второго прямоугольника */ 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 < 0) || (height < 0)) return 0; return width * height; } 

Based on the text of the question, I believe that the coordinates grow from the lower left corner (if Y grows from top to bottom, amend the corresponding ones).

The idea is simple, illustrated in the picture (for the width, for the height is the same):

enter image description here

  • Visual Studio emphasizes max (), and with min () everything is ok - Oleksii Havryshkiv
  • 3
    After the picture appears, I want to vote "for" again. - Igor
  • @VladimirGamalyan what to do when emphasizes only max (), and min () not - Oleksii Havryshkiv
  • @OlexijHavryshkiv Write your function max . - Igor
  • one
    The origin of coordinates is usually denoted by the letter O, and not by two zeros - Pavel Mayorov