algorithm - 基本矩形分割

标签 algorithm language-agnostic

我被一些琐碎的问题困住了,好吧,我想我需要这里的帮助。

enter image description here

我有两个矩形,它保证它们从它们的 4 个基点(图片的上部)有一个公共(public)点。它也保证它们是轴对齐的。

我知道这些矩形的这个共同点(也很容易推导出来)、尺寸和坐标。


现在,我需要检索名为12 的矩形的坐标,我正在寻找一种简单的方法那(图片的下部)

我当前的实现依赖于许多 if 语句,我怀疑我太笨了,找不到更好的方法。

谢谢。

更新:我当前的实现。

Point commonPoint = getCommonPoint(bigRectangle, smallRectangle);

rectangle2 = new Rectangle(smallRectangle.getAdjacentVerticalPoint(commonPoint),
                           bigRectangle.getOppositePoint(commonPoint));

rectangle1 = new Rectangle(smallRectangle.getAdjacentHorizontalPoint(commonPoint)
                           bigRectangle.getOppositePoint(commonPoint));

// Now simply adjust one of these rectangles to remove the overlap,
// it's trivial - we take the 'opposite' points for 'small' and 'big'
// rectangles and then use their absolute coordinate difference as
// a fix for either width of 'rectangle2' or height of 'rectangle1'
// (in this situation it's going to be width).

adjustRectangle(rectangle2);

这是重构,但方法 getCommonPointgetAdjacent...getOpposite 仍然有许多 if 语句我想是否可以做得更好。

最佳答案

Rectangle 1 的 top 和 bottom 值与大矩形相同。矩形2的左右值与小矩形相同。我们只需要获取矩形 1 的左值和右值,以及矩形 2 的顶值和底值。所以我们只有 2 个简单的 if 语句:

if (bigRectangle.Left == smallRectangle.Left) 
    left = smallRectangle.Right
    right = bigRectangle.Right
else
    left = bigRectangle.Left
    right = smallRectangle.Left
rectangle1 = new Rectangle(left, bigRectangle.Top, right - left, bigRectangle.Height)

if (bigRectangle.Top == smallRectangle.Top)
    top = smallRectangle.Bottom
    bottom = bigRectangle.Bottom
else
    top = bigRectangle.Top
    bottom = smallRectangle.Top
rectangle2 = new Rectangle(smallRectangle.Left, top, smallRectangle.Width, bottom - top)

在上面,Rectangle 构造函数接受输入:left、top、width、height。

关于algorithm - 基本矩形分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7762000/

相关文章:

arrays - 在 ruby​​ 数组中查找并展平重叠的时间间隔

oop - 深度继承层次结构的替代方案?

algorithm - 树递归斐波那契算法需要线性空间?

c++ - 产生两个间隔集合的差异的算法

algorithm - 对于超过两名参赛者的回合,什么算法可以生成循环赛 "pairings"?

string - 用于测量两个字符串中出现的大小 >=2 的子序列数量的指标

algorithm - 了解 O(max(m,n)) 的时间复杂度

performance - 我什么时候应该考虑函数调用对性能的影响?

oop - 仅具有副作用的方法的名称

algorithm - 我在最近的一次采访中被问到这个