Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding unions of line segments on a number line

Tags:

algorithm

I have a number-line between 0 to 1000. I have many line segments on the number line. All line segments' x1 is >= 0 and all x2 are < 1000. All x1 and x2 are integers.

I need to find all of the unions of the line segments.

In this image, the line segments are in blue and the unions are in red:

enter image description here

Is there an existing algorithm for this type of problem?

like image 824
jedierikb Avatar asked Dec 04 '25 13:12

jedierikb


1 Answers

You can use marzullo's algorithm (see Wikipedia for more details). Here is a Python implementation I wrote:

def ip_ranges_grouping(range_lst):
    ##  Based on Marzullo's algorithm
    ##  Input: list of IP ranges
    ##  Returns a new merged list of IP ranges
    table = []
    for rng in range_lst:
        start,end = rng.split('-')
        table.append((ip2int(start),1))
        table.append((ip2int(end),-1))
    table.sort(key=lambda x: x[0])
    for i in range(len(table) - 1):
        if((table[i][0] == table[i+1][0]) and ((table[i][1] == -1) and (table[i+1][1] == 1))):
           table[i],table[i+1] = table[i+1],table[i]

    merged = []
    end = count = 0
    while (end < len(table)):
        start = end
        count += table[end][1]
        while(count > 0): # upon last index, count == 0 and loop terminates
            end += 1
            count += table[end][1]
        merged.append(int2ip(table[start][0]) + '-' + int2ip(table[end][0]))
        end += 1
    return merged
like image 56
Binyamin Avatar answered Dec 06 '25 04:12

Binyamin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!