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 as follows:

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

Any thoughts? Of course, I tried to use the most common "loop", but still did not get it.

+4
source share
3 answers

Here is 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; 
+4
source

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"; 
+12
source
 @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); 
+1
source

Source: https://habr.com/ru/post/1307509/


All Articles