添加到阵列的连续号码阵列、号码

2023-09-11 23:00:43 作者:选择奔跑

这是我要的话,我希望能得到正确的第一个问题。在PHP(如果你不能,Python或伪语言也没关系),给定n个元素的数组:

This is my first question to SO, I hope to get it right. In PHP (if you can't, python or pseudo language is also okay), Given an array of n elements:

old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]

我需要添加到一个新的数组连续的数字,如果它不是一个连续的编号只值添加到一个新的数组:

I need to add to a new array consecutive numbers, if it is not a consecutive number add only that value to a new array:

new_array = [ [1,2,3],
              [5],
              [7,8,9]
              [20,21]
              [23],
              [29]
            ]

下面的话,我发现这些相关的话题,但不能让它的工作。

Here on SO, i found these related topics, but can't get it to work.

Creating用连续的数字 列表的列表 Python找到N个连续号码列表 Find连续整数之和W / O在JavaScript 使用循环 Creating a list of lists with consecutive numbers Python finding n consecutive numbers in a list Find the sum of consecutive whole numbers w/o using loop in JavaScript

在code,这不是工作是在版本历史记录,我删除它,因为它是有格式问题。

The code that wasn't working is on the version history, I removed it because it's having formatting problems.

感谢所有,尤其是胡安,mistabell和Axsuul为提供正确的答案。

Thanks all, and especially Juan, mistabell and Axsuul for the providing the correct answer.

推荐答案

尽我所能想出是:

function subsequenceArray($values) {
    $res = array();
    $length = count($values);
    if (0 == $length) {
        return $res;
    }
    $last = 0;
    $res[$last] = array($values[0]);
    for ($i = 1; $i < $length; $i++) {
        if ($values[$i] == $values[$i-1] + 1) {
            $res[$last][] = $values[$i];
        } else {
            $res[++$last] = array($values[$i]);
        }
    }
    return $res;
}