That's the complete solution. You don't need to do all that work, though. Here's a much simpler regex solution:{ my @to_b36 = (0 .. 9, 'A' .. 'Z'); my %to_num; @to_num{@to_b36} = 0 .. 35; sub b36_to_num { my $n = shift; my ($i, $s) = (0, 0); $s += $to_num{chop $n} * 36**$i++ while length $n; return $s; } sub num_to_b36 { use integer; # so that /= 36 is easy my $n = shift; my $s = ""; do { $s = $to_b36[$n % 36] . $s, $n /= 36 } while $n; return $s; } sub inc_b36 { num_to_b36(&b36_to_num + 1) } }
You could also use my reversed regex approach:{ # in the same block as the previous code sub rx_inc_b36 { my $n = shift; $n =~ s/([^Z])(Z*)$/$to_b36[$to_num{$1}+1] . 0 x length $2/e or $n = 1 . 0 x length $n; return $n; } }
And here is my golf code, which registers 94 characters:{ # ditto sub rx_inc_b36 { my $n = reverse shift; $n =~ s/^(Z*)([^Z])/(0 x length $1) . $to_b36[$to_num{$2}+1]/e or $n = (0 x length $n) . 1; return scalar reverse $n; } }
sub GOLF { local$_=pop;@_{@_=( 0..9,A..Z)}=0..35;s /([^Z])(Z*)$/$_[$_{ $1}+1].$-x length$2 /e?$_:1 .$-x y!!!c }
_____________________________________________________
Jeff[japhy]Pinyan:
Perl,
regex,
and perl
hacker, who'd like a (from-home) job
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
In reply to Re: Base36 numbers: speed and golf
by japhy
in thread Base36 numbers: speed and golf
by nop
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |