On Tue, 7 Jan 2014 13:35:39 -0600
Hal Wigoda <hal.wig...@gmail.com> wrote: 
> On Tue, Jan 7, 2014 at 1:28 PM, Rajeev Prasad <.ne...@yahoo.com>
> wrote:
> > so i have this series of numbers:
> > [...]
> > there are two ranges in there: 349-396, 425-496
> >
> > any hints as to how to write a perl code to represent the series of
> > numbers as a range?

> (349..396,425..496);

The impression I got was that the OP wanted code to take that list of
numbers, and identify the ranges within.  I may be wrong, though.

If I'm right, though, simply looping through the range in numerical
order, checking if the number you're looking at is one higher than the
last, and either adding it to the "current" range if so, or starting a
new range if not, should be pretty easy - e.g. assuming @nums contains
that sorted list of numbers, then:


my @ranges;
my @current_range;
my $lastnum;

for my $num (@nums) {
    # See if we're starting a new range - if so, add the last range 
    # to the set of ranges we've found:
    if (@current_range && $num != $lastnum +1 ) {
        push @ranges, (@current_range > 1)
            ? $current_range[0] . '-' . $current_range[-1]
            : @current_range;
        @current_range = ($num);
    # Otherwise, just add this number to the current range
    } else {
        push @current_range, $num;
    }

    $lastnum = $num;
}

# Finally, when we've run out of numbers, we might have a remaining
range left # to add, so handle that:
if (@current_range) {
    push @ranges, (@current_range > 1)
        ? $current_range[0] . '-' . $current_range[-1]
        : @current_range;
}


There are likely shorter and more elegant ways than the above, though.

In fact, I'd be surprised if something like this doesn't exist on CPAN
already.

There's https://metacpan.org/pod/Number::Rangify which is most of hte
way there, but returns ranges as Set::IntRange objects, which is
probably a little OTT.


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to