In: Computer Science
c programming
Objectives:
Learn about conditional statements and Boolean operators.
Problem:
Let R and S be two rectangles in the xy-plane whose sides are parallel to the coordinate axes. Each rectangle is described by its center and its height and width. Determine if R and S overlap.
Example:
1) Suppose R is the rectangle centered at the origin height and width equal to one and S is the rectangle centered at the point (1,1) with a height equal to 2 and width equal to 3. Then L and S overlap.
2) Suppose R is the rectangle centered at the origin height and width equal to one and S is the rectangle centered at the point (100,100) with a height equal to 2 and width equal to 3. Then L and S do not overlap.
Bonus:
If two given rectangles as described above overlap, their intersection forms a new rectangle. Further determine its center, height, and width
CODE :
#include
#include
struct Rect
{
float x;
float y; // x,y co-ordinate of its center
float h; // height
float w; // width
};
int is_overlap(struct Rect a, struct
Rect b)
// checks whether the two rectangles overlap or not
// by checking whether the farthest points on the rectangle cross
each other or not
{
if ( a.x - a.w/2 >= b.x + b.w/2
) // a is on the right side of b
return 0;
if ( a.x + a.w/2
<= b.x - b.w/2 ) // a is on the left side of
b
return 0;
if ( a.y - a.h/2
>= b.y + b.h/2 ) // a is above b
return 0;
if ( a.y + a.h/2
<= b.y - b.h/2 ) // a is below b
return 0;
return 1;
}
float max(float a, float b)
{
if(a>b)
return a;
else
return b;
}
float min(float a, float b)
{
if(a
return a;
else
return b;
}
void print_overlap(struct Rect a,
struct Rect b)
{
float left = max(a.x - a.w/2, b.x -
b.w/2); // left is the x co-ordinate of the
left most point of the rectangle
float down = max(a.y - a.h/2, b.y -
b.h/2); // down is the y co-ordinate of the
lowest most point of the rectangle
float right = min(a.x + a.w/2, b.x + b.w/2
); // right is the x co-ordinate of the right most
point of the rectangle
float top = min(a.y + a.h/2, b.y +
b.h/2); // top is the y co-ordinate
of the top most point of the rectangle
struct Rect
c; // overlap rectangle
c.x = (left + right)/2;
c.y = (top + down)/2;
c.h = top - down;
c.w = right - left;
printf("\n\nOverLapped Rectangle : ");
printf("\nCenter : %.2f %.2f\n", c.x,
c.y);
printf("Height : %.2f\nWidth : %.2f", c.h,
c.w);
}
int main()
{
struct Rect a;
struct Rect b;
printf("Enter the center, the height, the width
of first rectangle : ");
scanf("%f %f %f %f", &(a.x), &(a.y),
&(a.h), &(a.w));
printf("Enter the center, the height, the width
of second rectangle : ");
scanf("%f %f %f %f", &(b.x), &(b.y),
&(b.h), &(b.w));
if(is_overlap(a,b) == 1)
{
printf("\nBoth the
rectangles overlap");
print_overlap(a,b);
}
else
{
printf("\nBoth the
rectangles don't overlap");
}
return 0;
}
Output :