aboutsummaryrefslogtreecommitdiff
path: root/challenge-006
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2019-05-04 16:19:14 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2019-05-04 16:19:14 +0100
commitf042cae50ee9684c2403c56d6ad2aafcd9778e3f (patch)
tree7cc5b04b82809f6333f2df7b8f25591180086bfa /challenge-006
parent4d9c788032a73de3199cb67bb27ba65c8df00deb (diff)
downloadperlweeklychallenge-club-f042cae50ee9684c2403c56d6ad2aafcd9778e3f.tar.gz
perlweeklychallenge-club-f042cae50ee9684c2403c56d6ad2aafcd9778e3f.tar.bz2
perlweeklychallenge-club-f042cae50ee9684c2403c56d6ad2aafcd9778e3f.zip
- Added solution by Guillermo Ramos.
Diffstat (limited to 'challenge-006')
-rw-r--r--challenge-006/guillermo-ramos/perl5/ch-1.pl34
1 files changed, 34 insertions, 0 deletions
diff --git a/challenge-006/guillermo-ramos/perl5/ch-1.pl b/challenge-006/guillermo-ramos/perl5/ch-1.pl
new file mode 100644
index 0000000000..5ec92037c5
--- /dev/null
+++ b/challenge-006/guillermo-ramos/perl5/ch-1.pl
@@ -0,0 +1,34 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+sub compact {
+ my @ns = split(/,/, shift);
+ my $from = my $to = shift @ns; # The first interval is the first number
+ my @intervals;
+
+ # Store the current interval ($from, $to) and advance to the next one
+ my $save = sub {
+ push(@intervals, $from == $to ? $from : "$from-$to");
+ $from = $to = shift;
+ };
+
+ # Iterate over the numbers, expanding the last interval or starting a new one
+ foreach my $n (@ns) {
+ if ($to == $n-1) {
+ $to = $n;
+ } else {
+ &$save($n);
+ }
+ }
+
+ # Store the last interval (except for empty input)
+ &$save if defined $to;
+
+ return join(",", @intervals);
+}
+
+foreach (@ARGV) {
+ print compact($_), "\n";
+}