Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday 24 March 2019

The Interview Question Today#25(20-3-19)(Rectangles overlap or not.)

Question:
Given two rectangles, find if the given two rectangles overlap or not.

Example:














Solution:

Approach:

Two rectangles do not overlap if one of the following conditions is true.
1) One Rectangle is inside other rectangle.

2) One rectangle is above the top edge of other rectangle.

3) One rectangle is on the left side of the left edge of other rectangle.



C program:

#include<stdio.h>

struct Point
{
int x, y;
};

int doOverlap(struct Point l1, struct Point r1,struct Point l2,struct Point r2)
{


    if(l1.x<=l2.x && l1.y>=l2.y && r1.x>=r2.x && r1.y>=r2.y)
        return 1;

    if(l1.x>=l2.x && l1.y<=l2.y && r1.x<=r2.x && r1.y<=r2.y)
        return 1;
// If one rectangle is not on left side of other

if (l1.x > r2.x || l2.x > r1.x)
return 0;


// If one rectangle is not above other
if (l1.y < r2.y || l2.y < r1.y)
return 0;

return 1;
}
int main()
{
struct Point l1,b1;
struct Point l2 ,b2;
printf("Enter the Coordinates of rectangle 1 length");
scanf("%d %d",&l1.x,&l1.y);
printf("Enter the Coordinates of rectangle 1 breath");
scanf("%d %d",&b1.x,&b1.y);
printf("Enter the Coordinates of rectangle 2 length");
scanf("%d %d",&l2.x,&l2.y);
printf("Enter the Coordinates of rectangle 2 breath");
scanf("%d %d",&b2.x,&b2.y);

if (doOverlap(l1, b1, l2, b2))
printf("Rectangles Overlap");
else
printf("Rectangles Don't Overlap");
return 0;
}


Output:



Enter the Coordinates of rectangle 1 length0

10

Enter the Coordinates of rectangle 1 breath10

25
Enter the Coordinates of rectangle 2 length11
20
Enter the Coordinates of rectangle 2 breath20
25
Rectangles Don't Overlap

0 comments:

Post a Comment