java - 返回所有矩形的并集

标签 java algorithm geometry computational-geometry rectangles

我对 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/

相关文章:

java - 将 beans 注入(inject) spring-batch item reader

python - 根据没有公共(public)列的坐标合并数据框

algorithm - 好的数据结构或数据库来表示对象和对象之间的转换?

algorithm - 实现 Kruskal 算法时是否必须使用 Union Find 数据结构?

algorithm - 临时组成员统计 - 有什么聪明的方法吗?

javascript - 将常规二维矩形坐标转换为梯形

python - Matplotlib 三角形 (plot_trisurf) 颜色和网格

java - 使用 java 8 计算列表中对象的属性

java - 我的世界 mod 1.12.2 玻璃虫

java - 如何在 JTextArea 上打印