in reply to eliding number ranges

A math way: (added two test cases for possible boundary problem)

use strict; use warnings; sub elide { my ($start,$end) = @_; if ((my $diff1 = length($end) - length($start)) > 0) { return "$start-$end"; } elsif ($diff1 == 0) { if ($start == $end) { return $start; } else { if ((my $diff2 = length($end) - length($end - $start)) > 0 +) { $end %= 10 ** (length($end) - $diff2); } return "$start-$end"; } } } while ( <DATA> ) { print elide( split ' ', $_ ), "\n"; } __DATA__ 1 32 4 19 28 39 34 123 321 321 324 329 325 349 340 509 999 1000 1000 1001

I tried to do it more math by using log10 to determine length, but that failed the second test case I added, because of rounding issue.

Replies are listed 'Best First'.
Re: Re: eliding number ranges
by Roy Johnson (Monsignor) on Nov 13, 2003 at 19:32 UTC
    Have you tried it with
    __DATA__ 28 31 199 201
    ? To get it to really work, I had to add a loop:
    sub elide { my ($start,$end) = @_; if ($end < $start) { ($start, $end) = ($end, $star +t) } elsif ($start == $end) { return $start } if (length($end) > length($start)) { return "$start-$end" } else { my $pow = 1; $pow *= 10 while int($end/$pow) > int($start/$pow); $end %= $pow; } return "$start-$end"; }
Re: Re: eliding number ranges
by melora (Scribe) on Nov 13, 2003 at 18:47 UTC
    I think the math approach is my favorite. The one suggestion I want to make, though, is more explicitly handling the situation where $start is larger than $end. It's not likely, but I've seen so much unlikely data in my time..