scott has asked for the wisdom of the Perl Monks concerning the following question:

Inspired by japhy's recent Snippets, I thought I'd try my hand at contructing my own function to convert a list into a string of ranges, e.g. ( 1,2,3,7,9,10,11,12) -> '1-3,7,9-12'.

Unlike japhy's totally cool regex-based solution, there's nothing nifty about my code.

I'd like to know what you think. Is it `good code'? Should I stick with my day job (which is pretty cool, IMHO -- so that wouldn't be too bad)?

I know I seem to have a surefit of ?:s and the push is duplicated but I wanted a single function so I didn't pull it out.

use strict; use warnings; # Convert ( 1,2,3,7,9,10,11,12) to '1-3,7,9-12'. # # Handles duplicate numbers (by ignoring them), reals, out # of order elements*, and changes in sign within the array. # # * Well, I guess I should say that it assumes you want # 'normal' order and not necessarily the order given. # sub num2range( @ ) { my ( @end_points , @ranges ); @_ = sort { $a <=> $b } @_; # Construct the first interval. $end_points[ 0 ] = $end_points[ 1 ] = shift; # We're done! ... Unless there's more than one element in # the array. :) @_ or return wantarray ? ( $end_points[ 0 ] ) : $end_points[ 0 ]; # Scan through the rest of the array, building on the # current endpoint until we get to a jump. Whereupon we # push the current endpoint into the list of ranges, and # initialize a new interval with the current element. for ( @_ ) { if ( $_ - $end_points[ 1 ] == 1 ) { $end_points[ 1 ]++; } else { unless ( $_ == $end_points[ 1 ] ) { push @ranges , ( $end_points[ 0 ] == $end_points[ 1 ] ) ? "$end_points[ 0 ]" : "$end_points[ 0 ]-$end_points[ 1 ]"; } @end_points = ( $_ , $_ ); } } # The last element is special since it has no antecedant # and, hence, will never be processed by the push above. push @ranges , ( $end_points[ 0 ] == $end_points[ 1 ] ) ? "$end_points[ 0 ]" : "$end_points[ 0 ]-$end_points[ 1 ]"; return wantarray ? @ranges : join( ',' , @ranges ); } # For example: # print scalar num2range( 1,2,2.5,3.5,4.5,7,6,-5,-6,-7,7,8,9,10,0,12,4 +2-24 ); # Gives: # -7--5,0-2,2.5-4.5,4.6,6-10,12,18

Scott
---------
Do not meddle in the affairs of dragons, for thou art crunchy and taste good with ketchup.

Replies are listed 'Best First'.
Re: Critique yet another List-to-Range function
by tachyon (Chancellor) on Jun 15, 2001 at 10:50 UTC

    I like your code but would suggest that the output is perhaps incorrect. Surely the two ranges 0-2,2.5-4.5 are a single logical range 0-4.5??? The range concept becomes a bit iffy once you stop using integers. Any two numbers will constitute a range - it just depends on your step size. Using my definition that a range means that any two adjacent numbers within that range are no more than unity apart....the range should be 0-4.5 not the 0-2,2.5-4.5...

    Anyway, did somebody say GOLF? A bloated 93 chars, surely well over par.

    cheers

    tachyon

    @test =(1,2,2.5,3.5,4.5,7,6,-5,-6,-7,7,8,9,10,0,12,18); sub range { @_=sort{$a<=>$b}@_;@r=($l)=$_[0]; map{if(abs$l-$_>1){push@r,$r=$_; $r[-2].="~$l";}$l=$_;}@_;@r; } @result = range(@test); print "$_\n" for @result; Prints: -7~-5 0~4.5 6~10 12~12 18

      Surely the two ranges 0-2,2.5-4.5 are a single logical range 0-4.5??? The range concept becomes a bit iffy once you stop using integers. Any two numbers will constitute a range - it just depends on your step size.

      Heh, thanks. Too true. I therefore implement your definition via the replacement:
      if ( $_ - $end_points[ 1 ] == 1 ) { $end_points[ 1 ]++; }
      goes to
      if ( $_ - $end_points[ 1 ] <= 1 ) { $end_points[ 1 ] = $_; }

      For posterity sake, I thought I'd note that there is a problem with this.
      #!/usr/bin/perl -w my @test = ((1..3), 5, (7..9), (11..12), (17..19)); sub range { @_=sort{$a<=>$b}@_;@r=($l)=$_[0]; map{if(abs$l-$_>1){push@r,$r=$_; $r[-2].="~$l";}$l=$_;}@_;@r; } my @ranged = range(@test); print "@test \n"; # prints 1 2 3 5 7 8 9 11 12 17 18 19 print "@ranged \n"; # prints 1~3 5~5 7~9 11~12 17


      -Lee

      "To be civilized is to deny one's nature."
      <golf>
      • 3 trailing-semi-colons rear their ugly heads! (#90)
      • $r= in the push ??? (#87)
      • abs can go in favour of if($_-$l>1) (#84)
      </golf>

      but all this is in vain as the code is flawed -- in your example 12 has its own range (12~12) and it's the same for any single integer that doesn't fall in a range.

      "Argument is futile - you will be ignorralated!"

Re: Critique yet another List-to-Range function
by chipmunk (Parson) on Jun 18, 2001 at 06:07 UTC
    A quick comment. This bit of code is redundant:
    return wantarray ? ( $end_points[ 0 ] ) : $end_points[ 0 ];
    A list is made by context, whether or not there are parentheses. Parentheses just provide precedence, as in print join('|', @cols), "\n". Either of these will work just as well, whichever context the function is called in:
    return $end_points[0]; return ( $end_points[0] );

    [There are a couple odd exceptions, such as the left hand side of the x operator. ($var x 3 returns a string, while ($x) x 3 returns a list.) But in general, parentheses are unnecessary around a list except for precedence.]