php - Add to array consecutive numbers -
this first question so, hope right. in php (if can't, python or pseudo language okay), given array of n elements:
old_array = [1, 2, 3, 5, 7, 8, 9, 20, 21, 23, 29]
i need add new array consecutive numbers, if not consecutive number add value new array:
new_array = [ [1,2,3], [5], [7,8,9] [20,21] [23], [29] ]
here on so, found these related topics, can't work.
- creating list of lists consecutive numbers
- python finding n consecutive numbers in list
- find sum of consecutive whole numbers w/o using loop in javascript
the code wasn't working on version history, removed because it's having formatting problems.
thanks all, , juan, mistabell , axsuul providing correct answer.
the best can came is:
function subsequencearray($values) { $res = array(); $length = count($values); if (0 == $length) { return $res; } $last = 0; $res[$last] = array($values[0]); ($i = 1; $i < $length; $i++) { if ($values[$i] == $values[$i-1] + 1) { $res[$last][] = $values[$i]; } else { $res[++$last] = array($values[$i]); } } return $res; }
Comments
Post a Comment