-1

we have two examples of rectangle:

 public static Rectangle rect1 = new Rectangle(20, 300, 400, 160);
 public static Rectangle rect2 = new Rectangle(150, 60, 230, 450);

The problem is to find an algorithm that finds all intersection points of these two rectangles

Steve Lillis
  • 3,263
  • 5
  • 22
  • 41
  • Sounds like a collision detection problem, http://stackoverflow.com/questions/335600/collision-detection-between-two-images-in-java – Danielson Jun 26 '15 at 08:30
  • 2
    This sounds more like maths than Java. If you understand the maths of it, the coding should be simple. (I'd say the intersection is a region rather than a specific set of discrete points though.) – Jon Skeet Jun 26 '15 at 08:30
  • there may be infinitely many solution as well as no solution for _Intersection points of 2 rectangles_ – mazhar islam Jun 26 '15 at 08:37

3 Answers3

2

You can get the intersection points using inbuilt methods intersection

    Rectangle rect1 = new Rectangle(20, 300, 400, 160);
    Rectangle rect2 = new Rectangle(150, 60, 230, 450);

    Rectangle intersection = rect1.intersection(rect2);
    System.out.println(intersection);
Madhan
  • 5,750
  • 4
  • 28
  • 61
0

You should do this:

public Area getRectanglesColisionArea(Rectangle rect1, Rectangle rect2){
    Area shape1 = new Area(rect1);
    Area shape2 = new Area(rect2);

    return shape1.intersect(shape2);
}

Returning area shape is the

To call the function just:

    Rectangle rect1 = new Rectangle(20, 300, 400, 160);
    Rectangle rect2 = new Rectangle(150, 60, 230, 450);
    Area result = getRectanglesColisionArea(rect1,rect2);

The Area result is the shape of the intersection, from there you can get the intersection points:

    Rectangle inters = result.getBounds();
    Double x1=inters.getX();
    Double y1=inters.getY();
    Double x2=inters.getX()+inters.getWidth();
    Double y2=inters.getY()+inters.getHeight();
Bepo
  • 52
  • 8
0

For 2 rectangles, there would be four cases for intersection,

  1. One is inside another or they are totally disjoint - No point of intersection.
  2. They share a single point - 1 point of intersection.
  3. They intersect at exactly four points.
  4. They share part of one or more sides - infinite points of intersection.

These conditions can be used to write tests to find the solution.

div
  • 573
  • 5
  • 10