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

后端 未结 16 2894
我在风中等你
我在风中等你 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:24

    Here's my Perl solution. Could be cleaner and faster, but it shows how it works:

    # Just in case it's not sorted...
    my @list = sort { $a <=> $b } ( 1, 3, 4, 5, 6, 8, 11, 12, 14, 15, 16 );
    
    my $range = [ $list[0] ];
    
    for(@list[1 .. $#list]) {
        if($_ == $range->[-1] + 1) {
            push @$range, $_;
        }
        else {
            print $#$range ? $range->[0] . '-' . $range->[-1] : $range->[0], "\n";
            $range = [ $_ ];
        }
    }
    

提交回复
热议问题