Jump to content

Check number sequence


mrmos

Recommended Posts

You could do this:

if(array_intersect($needle, $haystack) == $needle)
   echo "Sequence is in array";

 

That matches even if they are out of order, though. If you want to match the order too, you can just keep them as a string (or put them into a string) and simply match it with strstr or regex.

I think this should do the trick:

 

function checkSequence($array) {
    $lowest = min($array);
    $inSequence = true;
    $sizeof = sizeof($array);
    for ($i = 0; $i < $sizeof; ++$i) {
        if ($lowest !== $array[0]) {
            $inSequence = false;
            break;
        } else if (isset($array[$i + 1]) && $array[$i] > $array[$i + 1]) {
                $inSequence = false;
                break;
            }
        }
    }
    return $inSequence;
}

An even simpler solution would be:

 

if ($array == array_intersect(range(min($array), max($array)), $array))) {
    //in sequence
}

 

This will return true for:

 

$a1= array(1,2,3,4,5,6);

 

and returns false for:

 

$a2= array(3,4,5,12,15);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.