I'm kinda new to Java and have a problem I just can't wrap my head around.
- union (Rectangle ... rectangles) should return the rectangle given by the Union of all rectangles. If rectangles is empty, return null.
I've created a helper-Method to compute the union of 2 Rectangles and then somehow tried to integrate it into the union-Method with no success. I kinda have to do the same for the intersection of 2 Rectangles but also can't get it done.
Could you guys give me some help? Below is my code.
public class Rectangle {
int x, y, width, height;
public Rectangle(int xInput, int yInput, int widthInput, int heightInput) {
if (xInput <= 0 || yInput <= 0 || widthInput <= 0 || heightInput <= 0) {
return;
}
this.x = xInput;
this.y = yInput;
this.width = widthInput;
this.height = heightInput;
}
public static Rectangle union(Rectangle... rectangles) {
Rectangle s = new Rectangle(0, 0, 0, 0);
if (rectangles.length != 0) {
for (Rectangle r : rectangles) {
s = unionOfTwo(s, r);
}
return s;
} else {
return null;
}
}
public static Rectangle unionOfTwo(Rectangle rec1, Rectangle rec2) {
int x1 = Utils.min(rec1.x, rec2.x);
int x2 = Utils.max(rec1.x + rec1.width, rec2.x + rec2.width) - x1;
int y1 = Utils.min(rec1.y, rec2.y);
int y2 = Utils.max(rec1.y + rec1.height, rec2.y + rec2.height) - y1;
return new Rectangle(x1, y1, x2, y2);
}
}
s
as the first rectangle before thefor
loop, then update it in each iteration withunionOfTwo(s,r)
and return it after the loop has completed. – n314159y2
is wrong, the second argument tomax
should berec2.y + rec2.height
. – n314159