Last active
December 15, 2016 06:18
-
-
Save codingfox-rus/b3c7d79256997867d2fc97d7317bff98 to your computer and use it in GitHub Desktop.
Алгоритм для разбиения массива по последовательностям чисел
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = [2,3,4,8,9,10,14,15,16,20,21,22]; | |
// Вычисляем "пропуски" - индексы массива, на которых последовательность прерывается | |
$skips = []; | |
$start = $arr[0]; | |
for ($i = 1; $i < sizeof($arr); $i++) { | |
if (($arr[$i] - $start) > 1) { | |
$skips[] = $i; | |
} | |
$start = $arr[$i]; | |
} | |
// Добавляем дополнительный индекс в пропуски для удобства вычислений | |
$skips[] = sizeof($arr); | |
// Разделяем массив на подмассивы с учетом пропусков | |
$chunks = []; | |
$begin = 0; | |
foreach ($skips as $skip) { | |
$chunks[] = array_slice($arr, $begin, $skip - $begin); | |
$begin = $skip; | |
} | |
print_r($chunks); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment