Overlapping Rectangles,

closed account (yp9h0pDG)



#include <iostream>

using namespace std;



int main() {


int rect1_Xa, rect1_Xb, rect1_Ya, rect1_Yb, rect2_Xa, rect2_Xb, rect2_Ya, rect2_Yb, maxYr1, maxXr1, maxYr2, maxXr2, minYr1, minXr1, minYr2, minXr2;

cin>> rect1_Xa >> rect1_Ya;
cin>> rect1_Xb >> rect1_Yb;
cout<<endl;
cin>> rect2_Xa >> rect2_Ya;
cin>> rect2_Xb >> rect2_Yb;
//Rectangle 1
if(rect1_Xa < rect1_Xb){

rect1_Xa=minXr1;
rect1_Xb=maxXr1;
}else {
rect1_Xa=maxXr1;
rect1_Xb=minXr1;
}

if(rect1_Ya > rect1_Yb){
rect1_Ya=maxYr1;
rect1_Yb=minYr1;
}else {

rect1_Ya=minYr1;
rect1_Yb=maxYr1;
}
//Rectangle 2
if(rect2_Xa < rect2_Xb){

rect2_Xa=minXr2;
rect2_Xb=maxXr2;
}else {
rect2_Xa=maxXr2;
rect2_Xb=minXr2;
}

if(rect2_Ya > rect2_Yb){
rect2_Ya=maxYr2;
rect2_Yb=minYr2;
}else {

rect2_Ya=minYr2;
rect2_Yb=maxYr2;
}


if((maxXr2 < minXr1) || (minXr2 > maxXr1)|| (maxYr2 < minYr1) || (minYr2 > maxYr1)){

cout<<"no overlap";
}else{
cout<<"overlap";
}
}






Last edited on
Google "axis-aligned rectangle overlap" or "... intersection".
Under Windows you can use the IntersectRect function.
https://msdn.microsoft.com/en-us/library/windows/desktop/dd145001(v=vs.85).aspx
You never initialize the min* and max* variables so when you use them, you're getting junk.

I'd do it like this:

- Given the points of opposite corners, figure out the top, bottom, left and right edges of the rectangle.
- Do the same with the other rectangle. Since you're doing the same thing twice, make it a function.

To decide if rectangles overlap, it's easiest to figure out if they don't overlap first. Two rectangles A and B don't overlap if A is above, below, to the right, or to the left of B:
A.bottom > B.top || A.top < B.bottom || A.right < B.left || A.left > B.right
And since they either overlap or they don't, just take the "not" of that value to determine if they overlap.
closed account (yp9h0pDG)
@dhayden
Thanks, for the help!
But, I don't think the problem is on initializing the min and max, because when i compile there is no error, but the solution is wrong , for ex. if i type the coordinates of 2 rectangles that overlap, the program writes "no overlap".
Also, how can i make it a function? I'm having difficulties at understanding how a function works.
Last edited on
I don't think the problem is on initializing the min and max, because when i compile there is no error,

Just because it compiles doesn't mean it will work. If you enable warnings when you compile, it will probably complain about the uninitialized variable.
how can i make it a function?

Please read this tutorial:
http://www.cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.