Dave Gordon Dave Gordon - 4 years ago 97
C# Question

C# iterate a continuously growing multi dimensional array

Imagine I wanted to iterate from A to Z. We would use either

Foreach
or
For
loop. After attaining Z I would then like to iterate from AA to ZZ, so it starts at AA, then goes to AB, AC...AZ, BA, BC..BZ..ZA,ZB, ZZ. At which point we would move to three
chars
, then 4 etc up to an undefined point.

Because we don't have a defined length for the array we cannot use nested
for
loops... so

Question: How can this be done?

Note, No code has been given because we all know how to
foreach
over an array and nest
foreach
loops.

Answer Source

The way to go is to use simple recursive approach. C# is a good language to present an idea with the use of generators:

private static IEnumerable<string> EnumerateLetters(int length) {
    for (int i = 1; i <= length; i++) {
        foreach (var letters in EnumerateLettersExact(i)) {                  
            yield return letters;
        }
    }
}

private static IEnumerable<string> EnumerateLettersExact(int length) {
    if (length == 0) {
        yield return "";
    }
    else {
        for (char c = 'A'; c <= 'Z'; ++c) {
            foreach (var letters in EnumerateLettersExact(length - 1)) {
                yield return c + letters;
            }
        }    
    }
}

private static void Main(string[] args) {
    foreach (var letters in EnumerateLetters(2)) {
        Console.Write($"{letters} ");
    }
}

EnumerateLetters generates successive sequences of letters. The parameter decides up to which length would you like to request sequences.

EnumerateLettersExact takes care of generating sequences recursively. It can either be empty or is a concatenation of some letter with all sequences of shorter length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download