Word Generation from Custom Alphabet – Base 26 Operations

Recently I’ve developed a brute force password cracker tool (can be found in post BruteForcer). I think it deserves to mention some design characteristics of the application. I’ll mention Alphabet Generation in other words base 26 operations that is used and needed for many programmers.

Alphabet to Generate

Our generator should output strings based on the alphabet that we provide. For instance if our alphabet was:

Alphabet = “ABC”

then our strings will be as below:

A AA BA CA AAA
B AB BB CB AAB
C AC BC CC AAC

In fact this is the base operations of the calculus.

This is a good link that gives the big picture more clearly for the whole English Alphabet: https://www.minus40.info/sky/alphabetcountdec.html

A = 1, B=2, C=3, AA = 4, AB = 5 and so forth.

Let’s check why AA = 4:

This is similar (but not same) with our base 10 number system because in base 10 we have zero (0). Pay attention that we do not write 00 as a number. But in string notation 00 is completely different than 0.

Alphabet size = 3, so we’ll use mod 3.

A = 1

B = 2

C =3

AA = (3*1) + 1 = 4

AB = (3*1) + 2 = 5

AAA = (3*3*1) + (3*1) + 1 = 13

and so forth.

Code

So below code gets string representation of any given integer for the given alphabet:

def int2base(self, x, base):
    if x == 0:
        return Config.ALPHABET[0]

    digits = []

    while x:
        x -= 1
        digits.append(Config.ALPHABET[x % base])
        x //= base # make sure it IS a integer division

    digits.reverse()

    result = ''.join(digits)

    if len(result) > Config.MAX_LENGTH:
        logging.warning('All combinations exhausted!')
        exit(0)

    return result

If you noticed there is a modulus and division operation in the loop. This is very similar to our base conversation calculation learned at our calculus lessons. Another important code is:

x //= base

which guarantees the integer division.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s