首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最小间距的物体间距算法

最小间距的物体间距算法
EN

Stack Overflow用户
提问于 2017-04-16 00:21:00
回答 1查看 119关注 0票数 0

在笛卡儿平面上,给定一堆随机小尺寸的矩形(通常为每面3-8个),每个矩形的左上角都被指定为x,y坐标,在-1到1之间随机分配,我如何将它们最小地展开,这样就不会出现保持其相对x,y位置的重叠?

我想要一个javascript的答案,但是任何可读的代码都可以。

下面是一些快速而简单的javascript来实现它:

代码语言:javascript
复制
for(some_number_of_rectangles)
  squares.push({
    x:random(-1,1), 
    y:random:(-1,1), 
    width:random(3,8), 
    height:random(3,8)
  })

示例输出:

代码语言:javascript
复制
[ 
  {x:0.5,y:0,width:2,height:2}, //intersects 3rd
  {x:0,y:1,width:2,height:2}, // intersects 4th
  {x:-1,y:0,width:2,height:2},
  {x:0,y:-0.5,width:2,height:2}, //intersects 5th
  {x:0,y:-1.5,width:2,height:2}
] // to simplify the problem, the sizes are all the same, but that won't be the case usually

及其解决办法:

代码语言:javascript
复制
[ // no intersections now
  {x:1,y:0,width:2,height:2}, // movement: 0.5
  {x:0,y:2,width:2,height:2}, // movement: 1
  {x:-2,y:0,width:2,height:2}, // movement: 1
  {x:0,y:-1,width:2,height:2} // movement: 0.5
  {x:0,y:-3,width:2,height:2} // movement: 1.5
]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-16 01:50:38

伪码:

代码语言:javascript
复制
factor = 0
for a in rectangles:
    for b in rectangles:
        factor = max(
            factor,
            min(
                max(
                    a.width / (b.x - a.x),
                    b.width / (a.x - b.x)
                ),
                max(
                    a.height / (b.y - a.y),
                    b.height / (a.y - b.y)
                )
            )
        )
// now multiply all coordinates with factor

推理:之后,每一对矩形,也可以。

代码语言:javascript
复制
factor >= a.width / (b.x - a.x) and factor >= b.width / (a.x - b.x)

代码语言:javascript
复制
factor >= a.height / (b.y - a.y) and factor >= b.height / (a.y - b.y)

现在假设,例如a.x <= b.xa.y <= b.y。然后在第一行

代码语言:javascript
复制
factor*b.x >= factor*a.x + a.width 

或者第二行

代码语言:javascript
复制
factor*b.y >= factor*a.y + a.height

因此,a和b不能同时重叠在x和y中,所以它们在2d不重叠。其他案件的处理方式类似。

根据factor的定义,这些不等式中至少有一个是相等的,因此得到的因子是最小的可能解。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43432504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档