Skip to content

Instantly share code, notes, and snippets.

@eqhmcow
Last active June 17, 2017 01:35
Show Gist options
  • Save eqhmcow/6ea174c0bd7b48813d0e0aae963260dc to your computer and use it in GitHub Desktop.
Save eqhmcow/6ea174c0bd7b48813d0e0aae963260dc to your computer and use it in GitHub Desktop.
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