【问题标题】:Algorithm that determines a relationship between a square and rectangle确定正方形和矩形之间关系的算法
【发布时间】:2011-02-05 09:11:24
【问题描述】:

我需要找到一种算法来确定正方形和矩形之间的关系。它必须能够确定:

  • 正方形完全在矩形内
  • 正方形部分位于矩形内部(重叠)
  • 正方形的角只接触矩形的角
  • 正方形的边在矩形的边上

以下是帮助我们为每种情况提取数学公式的输入(给定值):

  • 正方形中心的x坐标=squareX
  • 正方形中心的y坐标=squareY
  • 正方形的宽度 = squareW
  • 矩形中心的x坐标=recX
  • 矩形中心的y坐标=recY
  • 矩形的宽度 = recW
  • 矩形的长度 = recL

P.S:矩形的大小总是大于正方形的宽度。

一旦我们可以使用数学运算提取算法,我将用 Java 编写代码。

编辑:

对于接触角的情况,这是我写的代码,它可以工作(Math.abs 表示绝对值):

((Math.abs(Math.abs(recX-squareX)-(recW+squareW)/2))<=0.001) && ((Math.abs(Math.abs(recY-squareY)-(recL+squareW)/2))<=0.001)

【问题讨论】:

  • 请贴出你目前写的代码。人们通常不喜欢只为您编写代码。事实上,这是一个工作描述,而不是一个问题。
  • x 和 y 是如何精确定义的(左上角,中心,...)?
  • 你尝试过这个问题吗?
  • 是的,我确实尝试过,并且我能够做到角落的情况。请检查帖子,我已编辑。但我仍然需要算法的其余部分的帮助。
  • @lweller,我在帖子中解决了这个问题。所有坐标均指形状的中心。

标签: java algorithm math


【解决方案1】:

更新为双打

double dx = Math.abs(rectX - squareX);
double dy = Math.abs(rectY - squarey);
double dw2 = (rectW + squareW) / 2;
double dh2 = (rectL + squareW) / 2;

if (Double.compare(dx, dw2) == 0 && Double.compare(dy, dh2) == 0)
    return CORNER_TOUCH;
else if (Double.compare(dx, dw2) > 0 || Double.compare(dy, dh2) > 0)
    return OUTSIDE;
else if (Double.compare(dx, dw2) == 0 || Double.compare(dy, dh2) == 0)
    return EDGE_TOUCH;
else if (Double.compare(dx, rectW - dw2) <= 0 &&
        Double.compare(dy, rectL - dh2) <= 0)
    return INSIDE;
else 
    return OVERLAPS;

【讨论】:

  • 仅仅从你有一个返回 OVERLAPS 的 else 语句这一事实向我表明这个解决方案是错误的......
  • 感谢您的回复。除了边缘和角落,一切都很好。
  • @Falmarri,不,这只是表明您还没有阅读解决方案
  • @Dave 如果您使用双精度值,则需要采用此解决方案
  • 谢谢,我通过使用差异而不是相等来采用双打。
【解决方案2】:
squareX1 = squareX - squareW/2
squareY1 = squareY - squareW/2
squareX2 = squareX + squareW/2
squareY2 = squareY + squareW/2

recX1 = recX - recW/2
recY1 = recY - recL/2
recX2 = recX + recW/2
recY2 = recY + recL/2

inside = squareX1 > recX1 && squareX2 < recX2 && squareY1 > recY1 && squareY2 < recY2
overlaps = squareX1 < recX2 && squareX2 > recX1 && squareY1 < recY2 && squareY2 > recY1

最后两个应该是微不足道的

【讨论】:

  • 这也处理负坐标吗?我们应该在哪里添加绝对值?
猜你喜欢
  • 1970-01-01
  • 2015-03-05
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-14
  • 1970-01-01
相关资源
最近更新 更多