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

后端 未结 16 2890
我在风中等你
我在风中等你 2021-02-15 18:04

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         


        
16条回答
  •  悲&欢浪女
    2021-02-15 18:19

    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.

提交回复
热议问题