开发者

How can I get ranges from a list of integers in Perl?

I have an array of numbers:

@numbers = 1,2,3,6,8,9,11,12,13,14,15,20

and I want to print it this way:

1-3,6,8-9,11-15,20

Any thought开发者_开发百科s? Of course I tried using the most common "looping", but still didn't get it.


You can use Set::IntSpan::Fast:

use Set::IntSpan::Fast;

my @numbers = (1,2,3,6,8,9,11,12,13,14,15,20);

my $set = Set::IntSpan::Fast->new;
$set->add(@numbers);
print $set->as_string, "\n";


Here's one possible way:

@numbers = (1,2,3,6,8,9,11,12,13,14,15,20);
@list = ();
$first = $last = shift @numbers;
foreach (@numbers,inf) {
  if ($_ > $last+1) {
    if ($first == $last) {
      push @list, $first;
    } elsif ($first+1 == $last) {
      push @list, $first, $last;
    } else {
      push @list, "$first-$last";
    }
    $first = $_;
  }
  $last = $_;
}

print join ',', @list;


@numbers=sort { $a <=> $b } @numbers;
push @numbers, inf;

@p=();
$ra = shift @numbers;
$rb = $ra;
for $n (@numbers) {
  if ($n > $rb +1) {
      push @p, ($ra == $rb ? "$ra" : "$ra-$rb");

      $ra = $n;
  }

  $rb = $n;
}

print join(',', @p); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜