如何随机但平均分布节点在平面上 [英] How to randomly but evenly distribute nodes on a plane

查看:393
本文介绍了如何随机但平均分布节点在平面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在html5画布上放置1到100个节点(实际上是25px点)。我需要使它们看起来随机分布,所以使用某种网格是出来的。我还需要确保这些点不接触或重叠。我也想不要有大空白区域。有人可以告诉我这种算法叫什么?引用一个开源项目,这也是值得赞赏的。

I need to place 1 to 100 nodes (actually 25px dots) on a html5 canvas. I need to make them look randomly distributed so using some kind of grid is out. I also need to ensure these dots are not touching or overlapping. I would also like to not have big blank areas. Can someone tell me what this kind of algorithm is called? A reference to an open source project that does this would also be appreciated.

感谢所有

Guido

推荐答案

最简单的方法是只为每一个生成随机(x,y)坐标,如果它们接触或重叠则重复。

The easiest way would be to just generate random (x, y) coordinates for each one, repeating if they are touching or overlapping.

伪代码:

do N times
{
start:
  x = rand(0, width)
  y = rand(0, height)
  for each other point, p
    if distance(p.x, p.y, x, y) < radius * 2
      goto start
  add_point(x, y);
}

这是 O(n ^ 2) n 只有100,那就没问题了。

This is O(n^2), but if n is only going to be 100 then that's fine.

这篇关于如何随机但平均分布节点在平面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆