php - 组合算法中的循环

标签 php refactoring while-loop

我想执行特定类型的搜索。我不知道它是否有名称,但我可以描述它,并有执行它的工作代码。

对于二维矩阵,从点 0,0 开始并向右下方工作,搜索生成将如下所示:

  •   1、  4、  9、16、...
  •   2、  3、  8、15、...
  •   5、  6、  7、14、...
  • 10、11、12、13、...
  • ...

因此,第一个搜索循环将检查 1,第二个循环将检查 2、3、4,第三个循环将检查 5、6、7、8、9 等。

产生此搜索的代码是:

$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;
}

我对搜索被分成两个循环的方式不满意,因为循环内的代码几乎相同。您能否建议一种组合或嵌套循环并消除对 searchForPoint 的冗余调用的方法?

最佳答案

这样的事情怎么样

$pointFound = false;
$row = 0;

while(!$pointFound && $row < $matrixSize)
{
    $y = $row;
    $x = 0;
    while($y >= 0)
    {
        if (searchForPoint($matrix,$x,$y) !== false)
        {
            $pointFound = true;
            break;
        }

        // If we reached the right column, start moving upwards (decreasing y)
        if($x == $row)
            $y--;
        // Else move right
        else
            $x++;
    }
    // EDIT (forgot the next line)
    $row++;
}

关于php - 组合算法中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4878160/

相关文章:

php - 使用 PHP ZipArchive 将 zip 解压缩到特定目录

java - 更改为 void 或保留返回值

java - 如何修复 java 中 while 循环的条件

java - 这个条件在这个 while 循环中如何工作?

php - 集成 AJAX 和 PHP

php - 获取选定用户的位置

javascript - DOM 与 PHP 输出不匹配

function - Haskell 中的折叠实现

PHP:我应该传入并返回这些变量吗?

sql - 避免 SQL Server 中的 while 循环