这是我向SO提出的第一个问题,我希望能答对。在 PHP 中(如果你不会,Python 或伪语言也可以),给定一个包含 n 个元素的数组:
old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]
我需要向新数组添加连续数字,如果不是连续数字,则仅将该值添加到新数组中:
new_array = [ [1,2,3],
[5],
[7,8,9]
[20,21]
[23],
[29]
]
在这里,我找到了这些相关主题,但无法让它发挥作用。
- 创建具有连续数字的列表的列表 https://stackoverflow.com/questions/2408452/creating-a-list-of-lists-with-consecutive-numbers
- Python查找列表中n个连续的数字 https://stackoverflow.com/questions/2927213/python-finding-n-consecutive-numbers-in-a-list
- 在 JavaScript 中不使用循环求连续整数的总和 https://stackoverflow.com/questions/2843052/find-the-sum-of-consecutive-whole-numbers-w-o-using-loop-in-javascript
不起作用的代码位于版本历史记录中,我将其删除,因为它存在格式问题。
感谢所有人,特别是 Juan、mistabell 和 Axsuul 提供了正确的答案。