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
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 = [ $_ ];
}
}