So, similar to the neat feature of applying the ++ operator to a variable containing a string, but using only consonants as the "digits".$val = 'BB'; incr($val); ==> 'BC' $val = 'BZ'; incr($val); ==> 'CB'; $val = 'ZZ'; incr($val) ==> 'BBB';
I'm sure there must be a simple, slick Perl algorithm for incrementing using an arbitrary set of digits like this.
(UPDATE) Here's what I have written - I think it works, and it illustrates one way of doing it. Note that $digits can be any string of distinct characters and it will still "count".
use 5.010; use strict; use warnings; my $x = 'ZX'; for my $i ( 1 .. 100 ) { $x = incra($x); say $x; } sub incra { my $val = shift or die "Where's my value?"; $val = reverse $val; # easier to think left to right my $digits = 'BCDFGHJKLMNPQRSTVWXZ'; my $ndigits = length $digits; my $carry_in = 1; my $result = ''; for my $digit ( split //, $val ) { my $i = index $digits, $digit; if ($carry_in) { if ( $i == $ndigits - 1 ) { $digit = substr $digits, 0, 1; } else { $digit = substr $digits, $i + 1, 1; $carry_in = 0; } } $result .= $digit; } $result .= substr $digits, 0, 1 if $carry_in; return reverse $result; }
In reply to Algorithm for "Incrementing" strings by ibm1620
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |