#How to check if two rectangles overlap each other?

17 messages · Page 1 of 1 (latest)

sweet peak
#

plz tell me algorithm
I found the java code from online, but I can't understand it. bcz I am not familiar with java.```java
import java.util.Arrays;

class Main{

public static boolean isRectangleOverlap(int[] rec1, int[] rec2) {
    boolean widthIsPositive = Math.min(rec1[2 ], rec2[2]) > Math.max(rec1[0], rec2[0]);
    boolean heightIsPositive = Math.min(rec1[3], rec2[3]) > Math.max(rec1[1], rec2[1]);
    return ( widthIsPositive && heightIsPositive);
}

public static void main(String[] args) {
    int[] rec1 = {1,1,5,5};
    int[] rec2 = {1,7,10,12};

    System.out.println("Rectange 1 - " + Arrays.toString(rec1));
    System.out.println("Rectange 2 - " + Arrays.toString(rec2));
    boolean isOverlapping = isRectangleOverlap(rec1, rec2);
    System.out.println(isOverlapping?"The rectangles are overlapping":"The rectangles are not overlapping");
}

}

brave groveBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

charred merlin
#

@sweet peak You don't need to understand Java to understand the isRectangleOverlap function

#

It's basically english

night portal
#

Sit down with a piece of paper and draw a cartesian co-ordinate system. Draw 3 possibilities: one where the two rects are not overlapping, one where they are and one where one rect is inside the other. Then deduce rules as to how you know if one rectangle is intersecting another. Once you have the rules you can code it up easily.

neat zephyr
#

and saves you the terrible task of reading Java ^

night portal
#

Rectangles in programs are often described by listing their 4 vertices' coordinates e.g. a rectangle could be described as (1,1), (3,1), (3,4), (1,4)

#

The rules will use these cordinates somehow.

sweet peak
#

input :
rec1 :1 1 5 5
rec2 : 4 4 7 7
output :
yes

night portal
#

In the above Java snippet instead of having a list of four pairs of numbers (e.g. 8 numbers) it instead has one cordinate and two other numbers which are the width and height from that initial vertex.

#

so for rec1 (1,1) is the one of the corners of the rectangle and it has a width of 5 units and a height of 5 units

winged summit
#

are they axis-aligned rects?

brave groveBOT
#

This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.

brave groveBOT
#

This question thread is being automatically marked as solved.

sweet peak