我正在运行一个简单的脚本,它通过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>";
}
}
的functions.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;
}
答案 0 :(得分:0)
检查一下。重要我根据你的理论不知道这是不是。但如果你这样使用,它就不会给你错误。
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;
}