Javascript 最小间距对象的算法
在笛卡尔平面上给定一组随机小尺寸的矩形(通常每边3-8个),每个矩形的左上角作为x,y坐标随机分配在-1和1之间,我如何将它们最小程度地展开,以便不以保持其相对x,y位置的方式重叠 我希望有一个javascript的答案,但任何可读的代码都可以 下面是一些快速、简单的javascript代码:Javascript 最小间距对象的算法,javascript,algorithm,Javascript,Algorithm,在笛卡尔平面上给定一组随机小尺寸的矩形(通常每边3-8个),每个矩形的左上角作为x,y坐标随机分配在-1和1之间,我如何将它们最小程度地展开,以便不以保持其相对x,y位置的方式重叠 我希望有一个javascript的答案,但任何可读的代码都可以 下面是一些快速、简单的javascript代码: for(some_number_of_rectangles) squares.push({ x:random(-1,1), y:random:(-1,1), width:r
for(some_number_of_rectangles)
squares.push({
x:random(-1,1),
y:random:(-1,1),
width:random(3,8),
height:random(3,8)
})
该模型的输出示例:
[
{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
及其解决方案:
[ // 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
]
伪代码:
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
理由:
之后,对于每对矩形
factor >= a.width / (b.x - a.x) and factor >= b.width / (a.x - b.x)
或
现在假设,例如
a.x,您可以将传递给x.random()
的基数增加width:random()
乘以2,对于x平面两侧的填充,您的问题不清楚:如果您保留它们的相对x,y位置,您可以以什么方式将它们展开?我添加了示例输入和输出
factor >= a.height / (b.y - a.y) and factor >= b.height / (a.y - b.y)
factor*b.x >= factor*a.x + a.width
factor*b.y >= factor*a.y + a.height