Looking for a way to have a base36 sequence in C#

2.7k views Asked by At

In my application I use sequences. These are stored in Azure table storage as strings. To update the sequence I get the latest number as a string, convert to a number, add to the number and store it back as the current sequence value. The sequences are used internally as unique keys but they are also visible in URLs to the user so I would like to keep them short.

What I am considering is the idea of having a sequence in base36. In other words 0-Z. Does anyone have any idea how I can get a sequence that is stored as a 4 digit string starting with "0000" and then add one to it to give "0001" right through to "ZZZZ" as the last possible value of the sequence.

3

There are 3 answers

0
Vlad On BEST ANSWER

This should do it:

public static string Inc(string s){

    System.Func<char,int> v = c => (int)((c<='9')?(c-'0'):(c-'A'+10));
    System.Func<int,char> ch = d => (char)(d+((d<10)?'0':('A'-10)));    

    s = s.ToUpper();    
    var sb = new System.Text.StringBuilder(s.Length);
    sb.Length = s.Length;

    int carry = 1;
    for(int i=s.Length-1; i>=0; i--){
        int x = v(s[i])+carry;    
        carry = x/36;
        sb[i] = ch(x%36);
    }
    if (carry>0)
        return ch(carry) + sb.ToString();
    else
        return sb.ToString();
}
1
pil0t On

May be not most optimized, but very simple and can be used with different alphabet

private static void Main(string[] args)
{
    var letters = "0123456789abcdefghijklmnop".ToArray();

    var initial = "0000";

    for (int i = 0; i < 10000; i++)
    {
        initial = Increment(initial, letters);
        Console.WriteLine(initial);
    }

    Console.ReadLine();
}

public static string Increment(string input, char[] alphabet)
{
    var sa = input.ToArray();
    var lastChar = sa[sa.Length - 1];
    if (lastChar != alphabet.Last())
    {
        var index = Array.IndexOf(alphabet, lastChar);
        sa[sa.Length - 1] = alphabet[index + 1];
        return new string(sa);
    }

    return Increment(input.Substring(0, input.Length - 1), alphabet) + alphabet[0];
}
0
J. Holmes On

I have no idea if this is, in fact, what you are asking, but to get a List<string> starting at 0000 and ending at ZZZZ, you could do something like:

        var baseChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
        int radix = baseChars.Length, length = 4;
        var strings = Enumerable.Range(0, (int)Math.Pow(radix,length)).Select(value =>
        {
            var buffer = new string('0',length).ToCharArray();
            int i = length;
            do
            {
                buffer[--i] = baseChars[value%radix];
                value /= radix;
            } while (value > 0);

            return new string(buffer);
        }).ToList();