user8338613
user8338613

Reputation:

Area of intersection of two rectangles

I came across this interesting piece of code. It calculates the overlapping area of two rectangles.

#include <iostream>
using namespace std;


int overlapLine(int p11, int p12, int p21, int p22)
{
    int buf;

    buf = p11;
    p11 = min(p11, p12);
    p12 = max(buf, p12);

    buf = p21;
    p21 = min(p21, p22);
    p22 = max(buf, p22);

    return  max(0, max(0, p12 - p21) - max(0, p11 - p21) - max(0, p12 - p22));
}


int main(int argc, char* argv[])
{
    int x11 = -5, y11 = -5, x12 = 5,  y12 = 5;
    int x21 = -1, y21 = -1, x22 = 1,  y22 = 1;

    int w = overlapLine(x11, x12, x21, x22);
    int h = overlapLine(y11, y12, y21, y22);

    int overlapArea = w * h;
    cout << "OVERLAP AREA: " << overlapArea << endl;

    return 0;
}

The code works and produces correct result. However, I cannot understand how overlapLine gets the correct overlapping by X and Y axis.

Upvotes: 0

Views: 122

Answers (1)

gnetmil
gnetmil

Reputation: 86

Hope this answers your question: enter image description here

Upvotes: 3

Related Questions