tags:

views:

108

answers:

3

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 thoughts? Of course I tried using the most common "looping", but still didn't get it.

+4  A: 

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;
mobrule
thanks! it worked. :)
Suezy
+12  A: 

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";
cjm
There *is* a module for everything!
Robert P
+1  A: 
@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); 
Apprentice Queue