in reply to eliding number ranges
I'd solve it using a regex:
The way it works is this: if the lower and upper bounds are equal, just return the number; otherwise (assuming the upper bound is actually greater than the lower bound), we try to match a prefix in the lower bound that is also found in the upper bound (which could just be zero characters), and return the lower bound, a dash, and the remainder of the upper bound.sub elide_japhy { my ($s, $e) = @_; return $s == $e ? $s : ("$s $e" =~ /^(\d*)\d* \1(\d*)$/ and "$s-$2"); }
As an example, for 325 through 349, the prefix is '3', and the remainder is '49'; for 324 through 329, the prefix is '32', and the remainder is '9'.
Finally, we could micro-size it. It's not entirely golfed, but I get rid of intermediate variables.
Oh, and the logic could be embedded in the regex itself:sub elide_japhy { $_[0] == $_[1] ? shift : ("@_" =~ /^(\d*)\d* \1(\d*)$/ and "$_[0]-$2"); }
sub elide_japhy { "@_" =~ /^(\d*)(\d*) \1(?!\2)(\d*)$/ ? "$_[0]-$3" : shift; }
_____________________________________________________
Jeff[japhy]Pinyan:
Perl,
regex,
and perl
hacker, who'd like a job (NYC-area)
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: eliding number ranges
by Abigail-II (Bishop) on Nov 13, 2003 at 15:41 UTC | |
by japhy (Canon) on Nov 13, 2003 at 15:45 UTC |