I am trying to create in C# an alphanumeric counter that creates numbers in the following way:
0001 0002 0003 ... 9999 A000 A001 ... A999 B000 ...
The last number would be ZZZZ. So it would 0-9 first, then A-Z after that.
I am lost on how this can be done.
Update: After your comment I think there is a mistake in your question. What you probably want is just a simple base 36 counter. Here's one way you could implement it:
string base36Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string toBase36(int x, int digits)
{
char[] result = new char[digits];
for (int i = digits - 1; i >= 0; --i)
{
result[i] = base36Characters[x % 36];
x /= 36;
}
return new string(result);
}
IEnumerable<string> base36Counter()
{
for (int n = 0; n < 36 * 36 * 36 * 36; ++n)
{
yield return toBase36(n, 4);
}
}
void Run()
{
foreach (string s in base36Counter())
Console.WriteLine(s);
}
Original answer: I would probably implement it using yield:
IEnumerable<string> magicCounter()
{
// 0000, 0001, ..., 9999
for (int i = 0; i < 10000; ++i)
{
yield return i.ToString("0000");
}
// A000, A001, ..., Z999
for (char c = 'A'; c <= 'Z'; ++c)
{
for (int i = 0; i < 1000; ++i)
{
yield return c + i.ToString("000");
}
}
}
Edit: Updated to answer the clarified question.
The following code will generate the counter you describe:
0000, 0001... 9999, A000... A999, B000... Z999, ZA00... ZA99, ZB00... ZZ99, ZZA0... ZZZ9, ZZZA... ZZZZ
public const int MAX_VALUE = 38885;
public static IEnumerable<string> CustomCounter()
{
for (int i = 0; i <= MAX_VALUE; ++i)
yield return Format(i);
}
public static string Format(int i)
{
if (i < 0)
throw new Exception("Negative values not supported.");
if (i > MAX_VALUE)
throw new Exception("Greater than MAX_VALUE");
return String.Format("{0}{1}{2}{3}",
FormatDigit(CalculateDigit(1000, ref i)),
FormatDigit(CalculateDigit(100, ref i)),
FormatDigit(CalculateDigit(10, ref i)),
FormatDigit(i));
}
private static int CalculateDigit(int m, ref int i)
{
var r = i / m;
i = i % m;
if (r > 35)
{
i += (r - 35) * m;
r = 35;
}
return r;
}
private static char FormatDigit(int d)
{
return (char)(d < 10 ? '0' + d : 'A' + d - 10);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With