[英]Return union of all rectangles
我对 Java 有点陌生,遇到了一个问题,我无法解决。
我创建了一个辅助方法来计算 2 个矩形的并集,然后以某种方式尝试将它集成到并集方法中,但没有成功。 我有点不得不对 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;
}
将所有矩形转换为 [XMin, XMax] x [YMin, YMax] 表示。
找出最小值的最小值和最大值的最大值。
转换回 [XMin, Width] x [YMin, Height] 表示。
对于所有矩形的交集,类似地进行,但是
如果 Width 或 Height 结果为负,则交集无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.