Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing charaters past 'Z' in Java like a Spreadsheet

I didn't start too long ago with programming, and currently I need a method to produce an array, containing a character which is comes after the previous character. It should start with an 'A' at 0, then a B at '1' etc.. The hard part is making it so that after the 'Z' comes 'AA'.

What I came up with:

public static String[] charArray(int length)
{   
    String[] res = new String[length];
    for(int i = 0; i < length; i++)
    {
        String name = "";
        int colNumber = i;
        while(colNumber > 0)
        {
            char c = (char) ('A' + (colNumber % 26));
            name = c + name;
            colNumber = colNumber / 26;
        }
        res[i] = name;
    }
    return res;
}

This works fine for the first 26 letters of the alphabet, but it produces "... Y, Z, BA, BB, BC..." instead of "... Y, Z, AA, AB, AC..."

What's wrong? Or are there any more efficient or easier ways to do this?

Thanks in advance!

like image 747
Emiel Avatar asked Feb 15 '23 10:02

Emiel


1 Answers

You had a nice start. Instead of running through the while loop this example basically calculates the value of C based on the number % 26

Then the letter is added (concatenated) to the value within the array at the position: (index / 26) - 1 which ensures it's keeping up with the changes over time.

When iterating through on the first go, you'll have only one letter in each slot in the array A B C etc.

Once you've run through the alphabet, you'll then have an index that looks backwards and adds the current letter to that value.

You'll eventually get into AAA AAB AAC etc. or even more.

    public static String[] colArray(int length) {   

    String[] result = new String[length];

    String colName = "";
    for(int i = 0; i < length; i++) {

        char c = (char)('A' + (i % 26));
        colName = c + "";
        if(i > 25){
            colName =  result[(i / 26) - 1] + "" + c;
        }
        result[i] = colName;
    }
    return result;
}
like image 126
leigero Avatar answered Feb 17 '23 02:02

leigero