Skip to content

Instantly share code, notes, and snippets.

@eqhmcow
Last active Jun 17, 2017
Embed
What would you like to do?
aggregate contiguous positive numbers
use strict;
use warnings;
my @n;
while (<>) {
push @n, $_;
}
my $first_num = 0;
my $next_num = 0;
my $contig = 0;
my $last_num = 0;
push @n, -1;
while (1) {
my $n = shift @n;
$n || last;
chomp $n;
# initialize
unless ($next_num) {
$contig = 0;
$first_num = $n;
$next_num = $n + 1;
$last_num = $n;
next;
}
if ($n == $next_num) {
$contig = 1;
$last_num = $n;
$next_num = $n + 1;
next;
} elsif ($contig == 1) {
print "$first_num-$last_num\n";
# reinit
$next_num = 0;
unshift @n, $n;
next;
}
# no contig, just last number and unshift or end
print "$last_num\n";
# hit the end?
last if $n == -1;
# reinit
$next_num = 0;
unshift @n, $n;
}
while (<>) {
unless (m/-/) {
print "$_";
next;
}
m/(\d+)-(\d+)/;
for ($1..$2) {
print "$_\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment