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 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
The code that wasn’t working is on the version history, I removed it because it’s having formatting problems.
Thanks all, and especially Juan, mistabell and Axsuul for the providing the correct answer.
The best I can came up with is: