Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to generate alpha numeric sequence number based on input number

Tags:

c#

I am trying to develope a routine in C# that will take a given input integer and return a 6 character alpha numeric string based on a predefined possible set of characters.

The possible characters to use are:

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

Therefore given the input of 1, the output should be "000001", input of 9 would output "000009", input of 10 would output "00000A", input of 12345 would output "000AP3", and so on.

I am having a hard time coming up with an elegant solution to this problem. I know I must be approaching this the hard way so I'm looking for some help.

Thanks!

like image 767
Richard West Avatar asked May 12 '26 19:05

Richard West


2 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');
like image 112
LukeH Avatar answered May 16 '26 11:05

LukeH


The direct solution would simply be to iteratively divide your input value by N (the size of the character set), and take the remainder each time to index into the character set, and build up the output string character-by-character.

like image 37
Oliver Charlesworth Avatar answered May 16 '26 12:05

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!