我对 Java 有点陌生,有一个我无法解决的问题。
- union (矩形...矩形) 应该返回由 所有矩形的并集。如果矩形为空,则返回 null。
我创建了一个辅助方法来计算 2 个矩形的并集,然后尝试将其集成到联合方法中,但没有成功。我必须对两个矩形的交集做同样的事情,但也无法完成。
你们能给我一些帮助吗?下面是我的代码。
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);
}
}
最佳答案
问题出在这里:
public static Rectangle union(Rectangle... rectangles) {
Rectangle s = new Rectangle(0, 0, 0, 0); // <-- wrong
if (rectangles.length != 0) {
for (Rectangle r : rectangles) {
s = unionOfTwo(s, r);
}
return s;
} else {
return null;
}
}
这是因为如果你的矩形不重叠 (0, 0),你会得到错误的结果。有多种方法可以修复它,这是其中之一:
public static Rectangle union(Rectangle... rectangles) {
Rectangle s = null;
for (Rectangle r : rectangles) {
if (s == null)
s = r;
else
s = unionOfTwo(s, r);
}
return s;
}
关于java - 返回所有矩形的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022610/