i am looking for code that can generate an array where the first item is A, then B, then C . . .after Z it would then go to AA, then AB then AC . . . all the way up to ZZ.
what is the best way of doing this in C#?
One of the ways is:
IEnumerable<string> generate()
{
for (char c = 'A'; c <= 'Z'; c++)
yield return new string(c, 1);
for (char c = 'A'; c <= 'Z'; c++)
for (char d = 'A'; d <= 'Z'; d++)
yield return new string(new[] { c, d });
}
Edit:
you can actually produce "infinite" sequence (bounded by maximal long
value) with somewhat more complicated code:
string toBase26(long i)
{
if (i == 0) return ""; i--;
return toBase26(i / 26) + (char)('A' + i % 26);
}
IEnumerable<string> generate()
{
long n = 0;
while (true) yield return toBase26(++n);
}
This one goes like that: A, B, ..., Z, AA, AB, ..., ZZ, AAA, AAB, ... etc:
foreach (var s in generate().Take(200)) Console.WriteLine(s);
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