Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you display an array of integers as a set of ranges? (algorithm)

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
like image 996
Eran Galperin Avatar asked Sep 22 '08 21:09

Eran Galperin


2 Answers

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.

like image 160
Dima Avatar answered Sep 21 '22 15:09

Dima


Here's a python implementation, it should be easy enough to follow

numbers = [1,3,4,5,6,8,11,12,14,15,16];

def is_predecessor(i1, i2):
    if i1 == i2 - 1:
        return True;
    else:
        return False;

def make_range(i1, i2):
    if i1 == i2:
        return str(i1);
    else:
        return str(i1) + "-" + str(i2);

previous_element = None;
current_start_element = None;

for number in numbers:
    if not is_predecessor(previous_element, number):
        if current_start_element is not None:
            print make_range(current_start_element, previous_element);
        current_start_element = number;
    previous_element = number;

# handle last pair
if current_start_element is not None:
    print make_range(current_start_element, previous_element);

This outputs:

1
3-6
8
11-12
14-16

I know, I know, it isn't an algorithm, but I found it harder to actually explain it without having indentation problems than to just implement a solution for it.

like image 39
Lasse V. Karlsen Avatar answered Sep 22 '22 15:09

Lasse V. Karlsen