Function to generate an alphanumeric sequence number based on the input number

I am trying to develop a subroutine in C # that will take a given integer and return a 6-digit alphanumeric string based on a predefined possible character set.

Possible characters to use:

"0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" (note that the letters "I" and "O" are not included in the set.)

Therefore, given input 1, the output should be "000001", input 9 will output "000009", input 10 will output "00000A", input 12345 will output "000AP3", etc.

I find it difficult to find an elegant solution to this problem. I know that I must approach this uneasy, so I'm looking for some help.

Thank!

+3
source share
4 answers
int value = 12345;

string alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

var stack = new Stack<char>();
while (value > 0)
{
     stack.Push(alphabet[value % alphabet.Length]);
     value /= alphabet.Length;
}
string output = new string(stack.ToArray()).PadLeft(6, '0');
+7
source

A direct solution would be to simply iteratively divide your input value by N (character set size) and take the rest for indexing into a character set each time and grow the output line by character.

+1
source
internal class Program {
    private static void Main(string[] args) {
        int value = 38;

        const string alphabet = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        string result = ToBase(value, alphabet);
        Console.WriteLine(result);
    }

    private static string ToBase(int value, string alphabet) {
        if (value == 0) return alphabet[0].ToString();
        var result = new StringBuilder();
        while (value > 0) {
            int digit = value % alphabet.Length;
            value = (value - digit) / alphabet.Length;
            result.Insert(0, alphabet[digit]);
        }
        return result.ToString();
    }
}

you are doing zero padding

0
source

LukeH answer changed to generate Alphanemuric to numeric and vice versa

    int value = 12345;

    string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    var stack = new Stack<char>();
    while (value > 0)
    {
        int index = value % alphabet.Length;
        stack.Push(alphabet[index]);
        value /= alphabet.Length;
    }

    string output = new string(stack.ToArray()).PadLeft(6, '0');
    double intNumber = 0;
    int charPos = 0;
    for (var i = output.Length-1; i >=0;i--)
    {
        int val = output[i];
        if (val >= 48 && val <= 57)
            intNumber += (val - 48) * (Math.Pow(36, charPos++));
        else if (val >= 65 && val <= 90)
            intNumber += (val - 55) * (Math.Pow(36, charPos++));
    }
0
source

Source: https://habr.com/ru/post/1766247/


All Articles