我需要在具有一定宽度和高度的矩形上平均分配 N 个点。
前任。给定一个 10x10 的盒子和 100 个点,点将设置为:
(1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (1,8) (1,9) (1,10)
(2,1) (2,2) (2,3) (2,4) (2,5) (2,6) (2,7) (2,8) (2,9) (2,10)
(3,1) (3,2) (3,3) (3,4) (3,5) (3,6) (3,7) (3,8) (3,9) (3,10)
...
...
我如何将其概括为任何 N 点、宽度和高度组合?
注意:它不需要是完美的,但很接近,无论如何我都会随机化一点(从 X 和 Y 轴上的这个“起点”移动点 +/- x 像素),所以有一个剩下的几个点在最后随机添加可能就好了。
我正在寻找这样的东西(准随机):
最佳答案
我设法做到了,如果其他人希望做到这一点,请按以下方法进行:
首先你计算矩形的总面积,然后你计算每个点应该使用的面积,然后计算它自己的pointWidth和pointHeight(长度),然后迭代制作cols和rows,这里是一个例子。
PHP代码:
$width = 800;
$height = 300;
$nPoints = 50;
$totalArea = $width*$height;
$pointArea = $totalArea/$nPoints;
$length = sqrt($pointArea);
$im = imagecreatetruecolor($width,$height);
$red = imagecolorallocate($im,255,0,0);
for($i=$length/2; $i<$width; $i+=$length)
{
for($j=$length/2; $j<$height; $j+=$length)
{
imageellipse($im,$i,$j,5,5,$im,$red);
}
}
我还需要稍微随机化点的位置,我通过将它放在第二个“for”而不是上面的代码中来做到这一点。
{
$x = $i+((rand(0,$length)-$length/2)*$rand);
$y = $j+((rand(0,$length)-$length/2)*$rand);
imageellipse($im,$x,$y,5,5,$im,$red);
// $rand is a parameter of the function, which can take a value higher than 0 when using something like 0.001 the points are "NOT RANDOM", while a value of 1 makes the distribution of the points look random but well distributed, high values produced results unwanted for me, but might be useful for other applications.
}
希望这可以帮助那里的人。
关于algorithm - 在矩形上均匀分布 N 个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10579470/