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

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

问题描述

我需要在 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.

谢谢大家

圭多

推荐答案

最简单的方法是为每个坐标生成随机 (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天全站免登陆