PHP检查数组值是否连续


php check if array values are consecutive

我有一个数组$dice (4,7,3,6,7)

我需要一种方法来检查数组中的每个值是否都是连续的数字。

有简单的方法吗?

try this:

$dice = array(4,5,2,6,7);
function checkConsec($d) {
    for($i=0;$i<count($d);$i++) {
        if(isset($d[$i+1]) && $d[$i]+1 != $d[$i+1]) {
            return false;
        }
    }
    return true;
}
var_dump(checkConsec($dice)); //returns false
var_dump(checkConsec(array(4,5,6,7))); //returns true
function HasConsec($array)
{
    $res = false;
    $cb = false;
    foreach ($array as $im)
    {
        if ($cb !== false && $cb == $im)
            $res = true;
        $cb = $im + 1;
    }
    return $res;
}

我想这就是你要找的

for ($c = 0; $c < count($dice); $c++){
    $next_arr_pos = $c+1;
    if ($c == (count($dice) -1)){
        $cons_check = $dice[$c];
    }
    else
    {
        $cons_check = $dice[$next_arr_pos];
        $gap_calc = $cons_check-$dice[$c];
    }
    if ($dice[$c] < $cons_check && $gap_calc == 1){
        echo 'arr_pos = '.$dice[$c].' Is consecutive with '.$cons_check.' <br />';
    }
}

然而,我不是一个PHP开发人员,我知道这个问题看起来很老,但有一个简单的算法,我想和你分享,可以告诉你,如果你的数组是连续的或不

步骤如下:

  • 求输入数组的最大个数和最小个数

  • 应用方程:(max - min + 1) == array.length

  • 如果为真,则连续为假。

我想到了另一种方法:

$nums = [-1,0,1];
$nums = array_unique($nums); # optional, comment on the bottom
$range = range(min($nums), max($nums));
$diff = array_diff($range, $nums);
$isConsecutive = empty($diff) && count($nums) === count($range);

$nums = array_unique($nums) -如果您认为具有重复数字的数组也有效,则添加此值,例如[-1,0,1,1]

1//爱护你的内存!

2//只对1/1的增量有效(3.02,3.03,3.04,…consecutives !)

$x = ARRAY(9, 999999999);       // be careful!, RAM!
$x = ARRAY(99999997, 99999998, 99999999);
function concq_N($A){
    $tmp = $A[0];
    for($i = 1; $i < count($A); ++ $i){
        ++ $tmp;
        if($tmp != $A[$i])return false;
        }
    return true;
    }
echo(concq_N($x));

也许包含$scale_of_increment$direction的函数会很有趣:

$x = ARRAY(-99999997, -99999998, -99999999);

是连续的!,但是我的函数返回false xD