我有一个数字数组:
@numbers = 1,2,3,6,8,9,11,12,13,14,15,20
我想这样打印出来:
1-3,6,8-9,11-15,20
有什么想法吗?当然,我尝试了使用最常见的“循环”,但仍然没有得到它。
发布于 2010-04-21 13:45:47
这里有一种可能的方法:
@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;
发布于 2010-04-21 13:47:16
您可以使用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";
发布于 2010-04-21 14:06:52
@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);
https://stackoverflow.com/questions/2680539
复制相似问题