Generating an alphabetic sequence in Java

mip picture mip · Jan 3, 2012 · Viewed 25.5k times · Source

I'm looking for a way of generating an alphabetic sequence:

A, B, C, ..., Z, AA, AB, AC, ..., ZZ.

Can anyone suggest a convenient way of doing this. What data structures can I make use of?

I'd like methods which get the next code in the sequence and then reset the sequence.

Answer

user988346 picture user988346 · Jan 6, 2014

I combined Wikipedia's Hexavigesimal#Bijective base-26 and Bijective numeration#Properties of bijective base-k numerals to make this:

import static java.lang.Math.*;

private static String getString(int n) {
    char[] buf = new char[(int) floor(log(25 * (n + 1)) / log(26))];
    for (int i = buf.length - 1; i >= 0; i--) {
        n--;
        buf[i] = (char) ('A' + n % 26);
        n /= 26;
    }
    return new String(buf);
}

With the help of Wolfram Alpha. Maybe it would have been simpler to just use the implementation in the first link though.