Search code examples
c#asp.net.net

Best way to create an alphanumeric unique code generator in C# based on previous codes


I'm trying to create aN unique alphanumeric code generator using C# but I can't figure how to accomplish it. Here is the explanation:

Lets take an already generated code with this format: AA-0000000000-AA. Two chars, ten numbers, and two more chars. The thing is, I want to make a function to generate a new code based on that already generated one (in a real world application, the function would receive the latest generated code). So, the next code should be AA-00000000000-AB, the characters should increase one by one, so the limit of the code generator would be ZZ-9999999999-ZZ.

I've tried a couple different ways to make that but I can't find a way to increment the numbers and characters by one, so the only thing I have right now is this:

    public static string BarcodeGenerator(string latestBarcode)
    {
        string[] barcodeParts = latestBarcode.Split('-');
        
        string firstPart = barcodeParts[0];
        string secondPart = barcodeParts[1];
        string thirdPart = barcodeParts[2];
        
        return $"First part is {firstPart}, Second part is {secondPart}, Third part is {thirdPart}";
    }

I will continue trying to make it but just in case I'm posting the question here so I can get some help. Thank you!


Solution

  • Ideally, I would keep track of the latest index you're up to and generate from that.

    This code will let you do that:

    long letters = 26L * 26L;
    long digits = 10000000000L;
    
    string GetAlpha2(long value) => $"{(char)('A' + (value / 26L))}{(char)('A' + (value % 26L))}";
    string GetCode(long value) => $"{GetAlpha2(value / (letters * digits))}-{((value / letters) % digits):0000000000}-{GetAlpha2(value % (26L * 26L))}";
    

    Just keep counting up from 0 for the value passed to GetCode and you'll generate all of your codes.

    Try running this:

    Console.WriteLine(GetCode(0));
    Console.WriteLine(GetCode(letters - 1));
    Console.WriteLine(GetCode(letters * digits - 1));
    Console.WriteLine(GetCode(letters * digits));
    Console.WriteLine(GetCode(letters * digits * letters - 1));
    

    You get out:

    AA-0000000000-AA
    AA-0000000000-ZZ
    AA-9999999999-ZZ
    AB-0000000000-AA
    ZZ-9999999999-ZZ
    

    It's generating all of the correct codes.

    If you have to parse then try this:

    long ParseAlpha2(string code) => 26 * (code[0] - 'A') + code[1] - 'A';
    long ParseCode(string code) => code.Split('-').Select((x, n) => n switch { 0 => ParseAlpha2(x) * letters * digits, 1 => long.Parse(x) * letters, 2 => ParseAlpha2(x), _ => 0 }).Sum();
    

    Those are both tested, but fragile on input.