[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Formatting integer sets with ranges



Yitzchak Scott-Thoennes wrote:
> 
> I'll never need the script again, but it seems like there should be a
> somewhat simpler way to do this (along the lines of "print map ...").

Here's one that uses map:

sub int_ranges(@) {
  my @a = sort { $a <=> $b } @_;
  my @s = ([shift @a]);

  for ( @a ) {
    if ( $_ == $s[-1][-1]+1 ) {
      push @{ $s[-1] }, $_;
    }
    else {
      push @s, [$_];
    }
  }

  local $" = '-';
  join ',', map { $#$_ ? "@{$_}[0,-1]" : "@$_" } @s;
}

print int_ranges( 2, 5, 6, 3, 10, 1, 8 ), "\n";

# prints: 1-3,5-6,8,10


And here's one that works on the list as a string:

sub int_ranges(@) {
  @_ = map { $_, '-' } sort { $a <=> $b } @_;
  pop;
  local $_ = join '', map {
    $_[$_] eq '-' && $_[$_-1] != $_[$_+1]-1 ? ',' : $_[$_]
  } 0 .. $#_;
  s/-[^-]-/-/g;
  $_
}


Fun!

-- 
John Porter

"There are people who have fun studying the C++ spec for
literally seconds on end, I'm sure..."    John Vlissides


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe