Rectangles in a Cartesian plane are represented by a class Rectangle that has four private fields as shown:
class Rectangle{
private int left
private int bottom
private int width
private int height
e.Write a class method, intersection, that has two Rectangle parameters. The method should return the rectangle formed by the area common to the two rectangles. If they do not intersect, the method should return the rectangle whose instance fields are all zero. If the rectangles touch, the method should return a "rectangle" of zero width or zero length.
Please answer whole question which is question 8 on http://ntci.on.ca/compsci/java/ch6/6_10.html
public class Rectangle {
private int left;
private int bottom;
private int width;
private int height;
public Rectangle(int left, int bottom, int width, int height) {
this.left = left > 0 ? left : 0;
this.bottom = bottom > 0 ? bottom : 0;
this.width = width > 0 ? width : 0;
this.height = height > 0 ? height : 0;
}
public String toString() {
return "base:(" + left + "," + bottom + ") w:" + width + " h:" + height;
}
public int area() {
return width * height;
}
public int perimeter() {
return 2 * (width + height);
}
public static Rectangle intersection(Rectangle a, Rectangle b) {
int xALeft = a.left;
int xARight = a.left + a.width;
int yATop = a.bottom + a.height;
int yABottom = a.bottom;
int xBLeft = b.left;
int xBRight = b.left + b.width;
int yBTop = b.bottom + b.height;
int yBBottom = b.bottom;
if (xBLeft > xARight || xALeft > xBRight || yABottom > yBTop || yBBottom > yATop) {
return new Rectangle(0, 0, 0, 0);
} else {
int left = Math.max(xALeft, xBLeft);
int right = Math.min(xARight, xBRight);
int bottom = Math.max(yABottom, yBBottom);
int top = Math.min(yATop, yBTop);
return new Rectangle(left, bottom, right - left, top - bottom);
}
}
public static int totalPerimeter(Rectangle a, Rectangle b) {
return a.perimeter() + b.perimeter() - intersection(a, b).perimeter();
}
public boolean contains(Rectangle rectangle) {
return left <= rectangle.left && left + width >= rectangle.left + rectangle.width &&
bottom <= rectangle.bottom && bottom + height >= rectangle.bottom + rectangle.height;
}
}
Comments
Leave a comment