Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in c#, how can i build up array from A to ZZ that is similar to the way that excel orders columns

Tags:

c#

algorithm

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#?

like image 606
leora Avatar asked Mar 21 '11 22:03

leora


1 Answers

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);
like image 182
Vlad Avatar answered Oct 02 '22 23:10

Vlad