php - 检测数组 PHP 中的循环

标签 php arrays algorithm function cycle

我正在运行一个简单的脚本,它将一个整数放入 formula of the Collatz conjecture并将每个步骤的输出添加到数组中。

我想使用一个函数来检测数组中是否存在循环,使用 Floyd's algorithm .虽然我觉得我做得不错,但我似乎没有做对。此时我收到错误 Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12

请参阅下面的代码。非常感谢任何反馈!

    include("functions.php");

    $n = $_POST['number'];
    $step = 0;
    $reeks1 = array();
    $cycle = 0;
    echo "Your entry is: ". $n ."<br><br>";


    while($n!==1 && $cycle==0){
        $cycle = detect_cycle(array($reeks1));
            if($n % 2 == 0){
                $n = $n / 2;
                array_push($reeks1, "$n");
                $step++;
                echo $step .": ". $n ."<br>";
            }else{
                $n = ($n * 3) + 1;
                array_push($reeks1, "$n");
                $step++;
                echo $step .": ". $n ."<br>";
            }
        }

函数.php:

function detect_cycle($node){
    if ($node==NULL){
        return FALSE;
    }
    $turtle = $node;
    $rabbit = $node->next;
    while($rabbit != NULL){
        if($rabbit === $turtle){
            return TRUE;
        }elseif($rabbit->next == NULL){
            return FALSE;
        }else{
            $turtle = $turtle->next;
            $rabbit = $rabbit->next->next;
        }
    }
    return FALSE;
}

最佳答案

检查一下。重要我不知道这是根据你的理论。但如果你这样使用它不会给你错误。

function detect_cycle($node){
    if ($node==NULL){
        return FALSE;
    }
    $turtle = $node;
    $rabbit = $node[0];
    while($rabbit != NULL){
        if($rabbit === $turtle){
            return TRUE;
        }elseif($rabbit[0] == NULL){
            return FALSE;
        }else{
            $turtle = $turtle[0]; // use the number of the element key starting from 0
            $rabbit = $rabbit[0][1];
        }
    }
    return FALSE;
}

关于php - 检测数组 PHP 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897801/

相关文章:

c++ - 逗号在数组和结构初始化中的意义是什么?

PHP Laravel 同时执行多个 ajax 请求会出现 'encryption key' 服务器错误

php - 在 Laravel 中对多维数组应用搜索

php - laravel 中的 JSON 搜索 Eloquent

c# - 多调和样条实现c#

python - 两段算法之间的交集遗漏了交点

c - Mergesort 在执行时为已排序数组的第一个元素提供垃圾值

php - 如何从 Codeigniter 中的 URL 中删除 "&per_page="

javascript - 如果我选择索引值大于当前颜色索引的颜色,则只能覆盖通过 mousedown 应用的颜色

java - 在另一个类中处理一个类中的数组