ibm1620 has asked for the wisdom of the Perl Monks concerning the following question:
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; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Algorithm for "Incrementing" strings
by Not_a_Number (Prior) on Feb 11, 2015 at 19:22 UTC | |
by ibm1620 (Hermit) on Feb 11, 2015 at 19:27 UTC | |
Re: Algorithm for "Incrementing" strings
by pme (Monsignor) on Feb 11, 2015 at 18:27 UTC | |
by ibm1620 (Hermit) on Feb 11, 2015 at 18:32 UTC | |
by pme (Monsignor) on Feb 11, 2015 at 18:35 UTC | |
by MidLifeXis (Monsignor) on Feb 11, 2015 at 18:53 UTC | |
by pme (Monsignor) on Feb 11, 2015 at 20:23 UTC | |
Re: Algorithm for "Incrementing" strings (fleximal)
by tye (Sage) on Feb 12, 2015 at 01:52 UTC | |
Re: Algorithm for "Incrementing" strings
by Anonymous Monk on Feb 13, 2015 at 21:52 UTC | |
by Anonymous Monk on Feb 14, 2015 at 17:51 UTC | |
by Anonymous Monk on Feb 14, 2015 at 05:21 UTC | |
by tye (Sage) on Feb 15, 2015 at 03:51 UTC | |
A reply falls below the community's threshold of quality. You may see it by logging in. |