summaryrefslogtreecommitdiff
path: root/006/ch1.pl
blob: bac675c4bcc205ac09fae6c621819fac7fd2f101 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env perl
#
# Create a script which takes a list of numbers from command line and print the
# same in the compact form. For example, if you pass “1,2,3,4,9,10,14,15,16”
# then it should print the compact form like “1-4,9,10,14-16”
################################################################################

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