Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a rectangle is inside another rectangle [C]

Tags:

c

geometry

So I have two rectangles, the user has to input the bottom left point (x1,y1, but y1 is always 0) and the top right point (x2,y2), and I have to find out if one of them is completely inside the other (or they are exactly the same).

And it'll be a bit harder since I'll actually have to make the program so the user can decide how many rectangles they want to create, but at first I'd be happy to know how to check in the case of 2 rectangles.

like image 637
Mark Avatar asked Jan 04 '15 17:01

Mark


People also ask

Can you enclose any triangle inside a rectangle?

The claim is certainly true for a triangle. Any triangle can be embedded in a rectangle of twice its area.

How do you prove that four coordinates are a rectangle?

For a rectangle opposite sides are equal. You write coordinates of four vertices, apply distance formula of 3D for finding distance between any one pair of coordinates. In this way you will get 4 distances. Out of these distances if two distances are equal to each other then the given quadrilateral will be a rectangle.


2 Answers

Below is comparing the sides of the inner rectangle to the sides of the outer rectangle

if Right2 < Right1 && Left2 > Left1 && Top2 > Top1 && Bottom2 < Bottom1

Implementation:

struct RECT
{
    double x,y, w,h;

    RECT(double a,double b,double c,double d)
    {
    x=a; y=b; w=c; h=d;
    }
};


bool contains(RECT R1, RECT R2)
{
    if (   (R2.x+R2.w) < (R1.x+R1.w)
        && (R2.x) > (R1.x)
        && (R2.y) > (R1.y)
        && (R2.y+R2.h) < (R1.y+R1.h)
        )
    {
        return true;
    }
    else
    {
        return false;
    }
}
like image 80
Shahriar Avatar answered Oct 08 '22 13:10

Shahriar


Well, by definition one rectangle is inside of another if all the points of the inner rectangle are within the outer rectangle. Using a bit of geometry you can boil it down to checking whether the two opposite corners of the inner rectangle are in the outer rectangle.

like image 41
lared Avatar answered Oct 08 '22 12:10

lared