Skip to content

Commit 81f5d47

Browse files
authored
commit1-overlappingrectangles
1 parent 534f310 commit 81f5d47

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

OverlappingRectangles.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Created by Vatsal Gosaliya on 15-Jul-16.
3+
*
4+
* PROBLEM: Given are two rectangles defined over the 2-D cartesian coordinate system.
5+
* Each rectangle is expressed using the top-left corner, width and height.
6+
* The aim is to detect whether they overlap, and compute the overlapping
7+
* area, if they do.
8+
*/
9+
10+
class OverlappingRectangles {
11+
private double x,y,width,height;
12+
13+
OverlappingRectangles(double x, double y, double width, double height){
14+
this.x = x;
15+
this.y = y;
16+
this.width = width;
17+
this.height = height;
18+
}
19+
20+
OverlappingRectangles intersection(OverlappingRectangles rect2) {
21+
double newX = Math.max(this.x, rect2.x);
22+
double newY = Math.min(this.y, rect2.y);
23+
//System.out.println("newX = "+newX);
24+
//System.out.println("newY = "+newY);
25+
26+
double newWidth = Math.min(this.x + this.width, rect2.x + rect2.width) - newX;
27+
double newHeight = newY - Math.max(this.y - this.height, rect2.y - rect2.height);
28+
//System.out.println("newWidth = "+newWidth);
29+
//System.out.println("newHeight = "+newHeight);
30+
31+
if (newWidth <= 0d || newHeight <= 0d){
32+
System.out.print("No intersection.");
33+
return null;
34+
}
35+
36+
return new OverlappingRectangles(newX, newY, newWidth, newHeight);
37+
}
38+
39+
40+
public double getArea(){
41+
return this.width*this.height;
42+
}
43+
44+
public static void main(String args[]){
45+
OverlappingRectangles r1 = new OverlappingRectangles(2,8,3,4);
46+
OverlappingRectangles r2 = new OverlappingRectangles(1,7,6,2);
47+
OverlappingRectangles r = r1.intersection(r2);
48+
double areaOfIntersection = r == null ? 0 : r.getArea();
49+
System.out.print("Area of intersection : "+areaOfIntersection);
50+
}
51+
}

0 commit comments

Comments
 (0)