【问题标题】:Compute intersection of two identical objects计算两个相同对象的交集
【发布时间】:2018-02-25 12:27:39
【问题描述】:

我有 2 个Rectangles,它们的边缘相同。

new Rectangle(Arrays.asList(new Coord(1,1), new Coord(2,1), new Coord(2,2), new Coord(1,2)));

据我了解,Intersection 应该是1,但是我的函数返回-1

public Rectangle(List<Coord> edges){
        Assert.assertTrue("Provide an exact number of 4 edges", edges.size() == 4);
        this.edges = edges;
        left = getLeft(edges);
        right = getRight(edges);
        top = getTop(edges);
        bottom = getBottom(edges);
    }

private static int computeIntersection(Rectangle rect1, Rectangle rect2){

        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.bottom,rect2.bottom) - Math.max(rect1.top,rect2.top);
        System.out.println(x_overlap * y_overlap);


        return x_overlap * y_overlap;

    }

在计算交点时我的数学有问题吗?或者我没有考虑什么?

【问题讨论】:

  • x_overlap 是 1,y_overlap 是 -1。切换 x 或 y 的差异。
  • @luk2302 但这不是寻找交叉点的实际定义吗?!
  • 我对此表示怀疑,我不知道该值应该代表什么。它看起来很没有意义。如果有的话,我希望两个相同的对象为 0。我刚刚告诉过你,输出是预期的,看看你的代码,它是否有用或正确是完全不同的事情。
  • 你为什么发布这些方法getLeft、getTop等?您没有在代码中使用它们
  • 我愿意,设置值。我会更新的。

标签: java math intersection rectangles


【解决方案1】:

首先,你应该检查两个矩形是否真的重叠。

而且,您应该使用最小值top 减去最大值bottom

private static int computeIntersection(Rectangle rect1, Rectangle rect2){
    if (rect1.left >= rect2.right || rect2.left >= rect1.right
            || rect1.bottom >= rect2.top || rect2.bottom >= rect1.top) {
        return 0;
    } else {
        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.top,rect2.top) - Math.max(rect1.bottom,rect2.bottom);
        return x_overlap * y_overlap;
    }
}

【讨论】:

  • 完美,是的,我混淆了 y_overlap top and bottom。感谢您的澄清
猜你喜欢
  • 2019-11-30
  • 2019-02-20
  • 2020-07-14
  • 2021-02-24
  • 2018-03-19
  • 2012-02-12
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多