Re: Number to Letter Counting algorithim needed



On Jun 16, 12:38 pm, "Gary H" <nos...@xxxxxxxxx> wrote:

im trying to convert numbers into a character
sequence as such that A = 1 to Z = 26, but when
you get to 27 it becomes AA all the way to
702 which is ZZ then 703 is AAA

ie...

AAA
AAB
AAC
....
ABA
ABB
ABC

This time I am providing two subroutines which
do translations in both directions. The testing
part of my perl code illustrates the question.
Give it a "character sequence" (in the upper or
lower case, the algorithm doesn't care) and it
will give you the corresponding number, then
the string is computed back, as well as five
strings which follow it. Here is a conversation
with the program:

Enter (A-Z)-string ==> x
*** 24 ***
X Y Z AA AB AC


Enter (A-Z)-string ==> ax
*** 50 ***
AX AY AZ BA BB BC


Enter (A-Z)-string ==> cczx
*** 55456 ***
CCZX CCZY CCZZ CDAA CDAB CDAC


Enter (A-Z)-string ==> zzzz
*** 475254 ***
ZZZZ AAAAA AAAAB AAAAC AAAAD AAAAE


Enter (A-Z)-string ==> zzzzzx
*** 321272404 ***
ZZZZZX ZZZZZY ZZZZZZ AAAAAAA AAAAAAB AAAAAAC


Enter (A-Z)-string ==>

***
Entering nothing has stopped the converation.
And below, please find the (perl) code.

Regards,

Wlod

#!/usr/bin/perl
#
# wh, 2007-June

use Math::BigInt;
use integer;

$j = $n = Math::BigInt->new(0);

@alf =
qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);

$A = ord 'A';

sub intlet
{ @lab = ();
while($n)
{ --$n;
$r = $n % 26;
$n /= 26;
unshift @lab, $alf[$r]
}
}

sub letint
{ $j=Math::BigInt->new(0);
@ad = split //, $str;
for (@ad)
{ ($j *= 26) += ((ord $_) - $A + 1) }
}



#==========================#
#=== test test test ===#
#==========================#

sub cont
{ letint();
print " *** $j ***\n";
$n = Math::BigInt->new(0);
for (0..5)
{ $n = $j+$_;
intlet();
print " ", @lab
}
print "\n"
}

### main ###

while(1)
{ print "\nEnter (A-Z)-string ==> ";
chomp($str=<>);
last if !$str;
$str = uc $str;
cont();
print "\n"
}

.



Relevant Pages