I'm composing string values from the ordered set of consonants ('BCDFG .. Z') and I want to be able to increment them; e.g.
$val = 'BB'; incr($val); ==> 'BC' $val = 'BZ'; incr($val); ==> 'CB'; $val = 'ZZ'; incr($val) ==> 'BBB';
So, similar to the neat feature of applying the ++ operator to a variable containing a string, but using only consonants as the "digits".

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.