-1

My goal is to calculate the area of the complete figure in the coordinate plane, excluding the intersecting area. Can someone help me see what I need to fix?

#include <iostream>
#include <cstdlib>

using namespace std;

int minusOverlap(int lx, int ly, int rx, int ry, int llx, int lly, int rrx, int rry);

int main() {

cout << minusOverlap(1, 1, 3, 3, 2, 2, 5, 5);
}

int minusOverlap(int lx, int ly, int rx, int ry, int llx, int lly, int rrx, int rry){

 int a1, a2, overlap;

 //Calculate the area of rect 1 and 2
 //lower left is (lx, ly)
 //upper right is (rx, ry)

a1 = abs(rx-lx) * abs(ry - ly);
a2 = abs(rrx - llx) * abs(rry - lly);

//Calculate intersections using max and minus

overlap = (min(rx, rrx) - max(lx, llx)) 
*
 (min(rry, ry) * max(ly, lly));

   return a1 + a2 - 2*overlap; }
  • [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – PaulMcKenzie May 24 '20 at 03:45
  • You need to fix everything, by rewriting everything from scratch using correct algorithm and logic. The shown logic is fundamentally flawed. Even its design is wrong. This code should use a class or a struct to represent a single rectangle, and take two of them as parameters. This will allow things like checking for non-overlapping cases by reusing the same logic, for example, to check if rectangle A is to the right of B, or if B is to the right A. Ditto for up and down. And only after determining that none of those apply, it means that they must overlap, and ***then*** use min/max. – Sam Varshavchik May 24 '20 at 03:46

1 Answers1

0

I think you made a typo when calculating the overlap, it should (min(rry, ry) - max(ly, lly)); instead of (min(rry, ry) * max(ly, lly));

Assuming that you want this area:

enter image description here

here is the modified code:

#include <iostream>
#include <cstdlib>

using namespace std;

int minusOverlap(int lx, int ly, int rx, int ry, int llx, int lly, int rrx, int rry);

int main()
{
    cout << minusOverlap(1, 1, 3, 3, 2, 2, 5, 5);
}

int minusOverlap(int lx, int ly, int rx, int ry, int llx, int lly, int rrx, int rry)
{

    int a1, a2, overlap;

    //Calculate the area of rect 1 and 2
    //lower left is (lx, ly)
    //upper right is (rx, ry)

    a1 = abs(rx - lx) * abs(ry - ly);
    a2 = abs(rrx - llx) * abs(rry - lly);

    //Calculate intersections using max and minus

    overlap = (min(rx, rrx) - max(lx, llx)) * (min(rry, ry) - max(ly, lly));

    return a1 + a2 - 2 * overlap;
}

I am getting answer of 11, which is correct in this case

However, if you want this area:

enter image description here

you need to return return a1 + a2 - overlap; in the last line, instead of return a1 + a2 - 2 * overlap;

All this assumes that the rectangles are actually intersecting, if they are not intersecting, then it will give incorrect answer

Rishabh Gupta
  • 734
  • 6
  • 10