我正在运行一个简单的脚本,通过Collatz猜想公式将一个整数输入,并将每个步骤的输出添加到一个数组中。
我想使用一个函数来检测数组中是否有循环,使用Floyd算法。尽管我觉得我做得不错,但似乎并不正确。此时我收到错误信息
请参见我的代码。非常感谢您提供任何反馈!
我想使用一个函数来检测数组中是否有循环,使用Floyd算法。尽管我觉得我做得不错,但似乎并不正确。此时我收到错误信息
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;
}
$node
里有什么? - deEr.->next
来获取数组中的下一个元素。 - Nigel Ren