Turning number ranges into prefixes

David Cantrell david at cantrell.org.uk
Wed Aug 23 19:35:01 BST 2006

```On Wed, Aug 23, 2006 at 02:34:39PM +0100, David Cantrell wrote:

> I have a little problem that I could do with some help with.  I have
> data specifying number ranges.  For example, 1424210000 - 1424225999.  I
> need to turn that into a list of prefixes like 142421, 1424220, 1424221,
> 1424222, 1424223, 1424224, 1424225.  That range includes all the numbers
> of the right length with those prefixes, and no others.  Is there a
> terribly clever way of generating the list?

It's not terribly clever, but I came up with this.  It's the obvious
solution, so I can't help but think there's something better.  OTOH, it
appears to work, which is good enough for now.

...
print "\$min, \$max\n";

my @minprefixes = map { substr(\$min, 0, \$_) } reverse 1..length(\$min);
my @maxprefixes = map { substr(\$max, 0, \$_) } reverse 1..length(\$max);
my \$longest_prefix;
foreach(0 .. length(\$max) - 1) {
if(\$minprefixes[\$_] == \$maxprefixes[\$_]) {
\$longest_prefix = \$minprefixes[\$_];
last;
}
}
my @prefixes = try_prefix(\$longest_prefix, \$min, \$max);
print "  [".join(', ', @prefixes)."]\n";

sub try_prefix {
my(\$prefix, \$min, \$max) = @_;

my \$extradigits = length(\$min) - length(\$prefix);

if(
\$prefix.('0' x \$extradigits) >= \$min &&