[thelist] PHP algorithm help

RLivsey R.Livsey at cache-22.co.uk
Wed Sep 3 06:37:21 CDT 2003


Andy Warwick wrote:

> Hi
> 
> I figure I need some way to draw the grid row-by-row, generating the 
> valid slots for each row depending on the position of the image in the 
> row directly above.
> 

Hi Andy,

The following when supplied with the length of the row, the minimum 
seperation and the previous position, will return an array of valid 
positions for the next row.

<?php
function getValidPositions($length, $minSep, $prevPos)
{
	$upper = $prevPos + $minSep;
	$lower = $prevPos - $minSep;

	$valid = Array();

	for($i=0; $i<$length; $i++)
	{
		if($i>$upper || $i<$lower)
			$valid[] = $i;	

	}
	return $valid;
}

$valid = getValidPositions(8, 2, 4);
print_r($valid);
// Array ( [0] => 0 [1] => 1 [2] => 7 )
?>

Basically you want all results in between 0 and $length, who are more 
that $minSep away from the $prevPos.

You can then use that returned array and get a random value from it.

It's zero indexed whereas your example results were 1 indexed, but that 
won't be too hard to change.

HTH.

-- 
R.Livsey
Incutio Web Developer
[ PHP | Perl | Java | C# ]
www.cache-22.co.uk
www.incutio.com



More information about the thelist mailing list