I want to perform a specific-type of search. I do not know if it has a name, but I can describe it, and have working code for its execution.
For a 2-dimensional matrix, starting at point 0,0 and working down-right, the search generation would look like:
- 1, 4, 9, 16, ...
- 2, 3, 8, 15, ...
- 5, 6, 7, 14, ...
- 10, 11, 12, 13, ...
- ...
So the first search loop would inspect 1, the second loop inspects 2, 3, 4, the third loop inspects 5, 6, 7, 8, 9, etc.
The code to produce this search is:
$row_search = 0;
$point_not_found = true;
while ($point_not_found && $row_search < $matrix_height/2)
{
$current = array(0, $row_search);
while ($current[0] < $row_search)
{
if (searchForPoint( $matrix, $current ) !== false)
$point_not_found = false;
++$current[0];
}
if (!$anchor_not_found)
break;
while ($current[1] >= 0)
{
if (searchForPoint( $matrix, $current ) !== false)
$point_not_found = false;
--$current[1];
}
++$row_search;
}
I am unhappy with how the search is broken into two loops, as the code within the loops is nearly identical. Can you suggest a way to either combine or nest the loops and eliminate redundant calls to searchForPoint?