Reputation: 45
Higuys,
In Java, I wonder how can I determine if a square is inside a rectangle, or touching at the edges or touching at one corner, if these are given:
I know I have to use Math.abs() and find the x and y coordinate differences, but I could not formulate the problem mathematically.
All data types are doubles, by the way.
Even if you don't know Java, your ideas about mathematical formulation of this problem would be much appreciated.
Thanks in advance.
Upvotes: 1
Views: 4117
Reputation: 48619
Since you have not tagged this question as homework, I assume you can use the standard library methods:
static boolean isSquareInRectangle(sx, sy, sw, rx, ry, rw, rh) {
Rectangle2D s = new Rectangle2D.Double(sx, sy, sw, sw),
r = new Rectangle2D.Double(rx, ry, rw, rh);
return r.contains(s);
}
Upvotes: 1
Reputation: 3894
Just check to see if the top left corner falls within the bounds of the rectangle, and then compare the lengths of the width and height. The following is a simplified answer, and as you indicated, you'll need to implement Math.Abs() to correct for negative coordinates.
bool IsInside(Square s, Rectangle r) {
if (s.x < r.x) return false;
if (s.y > r.y) return false;
if ((r.Width - r.x) < (s.Width - s.x)) return false;
if ((r.Height - r.y) < (s.Width - s.y)) return false;
return true;
}
Upvotes: 1
Reputation: 27464
Is this homework?
The gist of the solution is to check the boundaries. Like:
boolean inside=square.x>=rectangle.x && square.x+square.width<=rectangle.x+rectangle.width
&& square.y>=rectangle.y && square.y+square.width<=rectangle.y+rectangle.height;
Upvotes: 0
Reputation: 22064
Irrespective of the language used, you can determine it by the following naive algorithm.
Test to see if all the points of the square lie inside the rectangle. You may want to define the function in such a way that, if a point of square touches the line of rectangle, it is considered to be inside.
Upvotes: 1