I need to equally distribute N points on a rectangle with a certain width and height.
Ex. given a 10x10 box and 100 points, the points would be set as:
(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)
...
...
How can I generalize this for any N points, width and height combination?
Note: It doesn't needs to be perfect, but close, I'm going to randomize this a little bit anyway (move the point +/- x pixels from this "starting point" on X and Y axis), so having a leftover of a few points to randomly add at the end could be just fine.
I'm looking for something like this (quasirandom):
I managed to make this, if anybody else is looking to accomplish this here's how:
First you calculate the total area of the rectangle, then you calculate the area every point should use, and then calculate its own pointWidth and pointHeight (length), then iterate to make cols and rows, here's an example.
PHP code:
$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);
}
}
I also needed to randomize the position of the dot a little bit, I made this by placing this in the 2nd "for" instead of the code above.
{
$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.
}
Hope this helps somebody out there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With