Question

I want to achieve something like this:

A, B, C, ...., Z, AA, AB, AC, ..., ZZ, AAA, AAB, AAC, ... AAZ, ABA, ABB, ABC, ... ABZ, .., ZZZ, AAAA, ....

i tried:

public String getSequence(int pos){     
    StringBuilder sb = new StringBuilder();
    int exponential, digit;
    int totalExponential = range;
    int maxExp = 0;
    int tempPos = 0;

    for(int i=1; tempPos < pos; i++, maxExp++) //loop to find the greatest exponent
        tempPos += (int)Math.pow(range, i);
    maxExp--; //greatest exponent is decremented by 1

    for(int i=1; i<maxExp; i++)
        totalExponential += (int)Math.pow(range, maxExp); 

    while(maxExp>0){
        exponential = (int)(Math.pow(range, maxExp));
        pos -= exponential;
        digit = (pos-1)/totalExponential;
        sb.append((char)(start+digit));
        totalExponential -= exponential;
        maxExp--;
    }       
}

It works fine until position 1378,

enter image description here

but bug shows on the next position

enter image description here

Does anyone have the code to achieve this. I preferred to have the recursion solution. Thanks

Was it helpful?

Solution

easier to go right to left.

try

public static String getSequence(int pos){
    StringBuilder sb = new StringBuilder();
    pos = pos -1;
    while (pos >= 0){
        sb.insert(0,(char)(start+(pos % range)));
        pos /= range;
        pos = pos -1;
    }

    return sb.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top