Suezy
Suezy

Reputation: 1111

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

Upvotes: 4

Views: 201

Answers (3)

Apprentice Queue
Apprentice Queue

Reputation: 2036

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

Upvotes: 1

cjm
cjm

Reputation: 62099

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

Upvotes: 12

mob
mob

Reputation: 118605

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;

Upvotes: 4

Related Questions