Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:
$numbers = ar
If the array is sorted in ascending order, then the problem is easy. Define a Range
structure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, update Range.end
, otherwise create a new range with this element as Range.begin
. Store the ranges to a dynamic array or a linked list. Or just print them out as you go.
If the array may not be sorted, then sort it first.