Creating sequential fixed size base 36 ids

996 Views Asked by At

I want to create a function which will give me fixed size 6 char alpha-numeric IDs with the requirement that the first and last character must be an alpha.

I want them to be generated sequentially. I think using base36 would be the way to go with an alphabet of [0-9A-Z] however I am not too sure how to ensure that they are always 6 char long with an alpha at the start and end.

E.g., if I create the IDs sequentially and start from 0, I would get 0 for output since 0 is the same in both bases.

Does anyone know of an efficient algorithm that could help here?

Thanks

1

There are 1 best solutions below

0
samgak On BEST ANSWER

You can use the standard algorithm for converting from an int to a base36 string, extracting one digit at a time by taking the modulo of the base and then dividing the remainder by the base, but add a special case for the first and last digit:

For e.g. in Java:

static String getId(int id)
{
    String s = "";
    for(int i = 0; i < 6; i++)
    {
        // compute the digit using modulo arithmetic using base 26
        // for first and last character and base 36 for others
        int digit;
        if((i == 0) || (i == 5))
        {
            digit = (id % 26) + 10;         
            id /= 26;
        }
        else
        {
            digit = id % 36;
            id /= 36;
        }

        // add the digit to the string:
        if(digit < 10)
            s = (char)('0' + digit) + s;
        else
            s = (char)('A' + (digit - 10)) + s;
    }
    return s;
}

There are 26*36*36*36*36*26 = 1135420416 possibilities, which means you only need a 32-bit integer to store them all.