如何从Perl中的整数列表中获取范围?

时间:2010-04-21 05:26:45

标签: perl arrays

我有一系列数字:

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

我想以这种方式打印:

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

有什么想法?当然我尝试使用最常见的“循环”,但仍然没有得到它。

3 个答案:

答案 0 :(得分:12)

您可以使用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";

答案 1 :(得分:4)

这是一种可能的方式:

@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;

答案 2 :(得分:1)

@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);