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 = array(1,3,4,5,6,8,11,12,14,15,16);
The ranges would be:
1,3-6,8,11-12,14-16
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the array is sorted in ascending order, then the problem is easy. Define a
Rangestructure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, updateRange.end, otherwise create a new range with this element asRange.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.