我正在运行一个简单的脚本,它将一个整数放入 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/