Search code examples
c#enumeration

enumerating over the alphabet from 'a' to 'zzz'


I'm wondering if it is possible to enumerate over the alphabet from 'a' to 'zzz'?

For example I have a cave system that contains a maximum of 1000 caves and I would like to assign a char value to each of them.

1 = a, 2 = b, 3 = c ... 27 = aa etc

What would be the best way to go about doing this if it is possible?


Solution

  • void Main()
    {
        foreach (string word in EnumerateCaveNames())
            Console.WriteLine(word);
    }
    
    IEnumerable<string> EnumerateCaveNames()
    {
        for (int i = 0; i < 26 * 26 * 26; ++i)
        {
            yield return BuildCaveName(i);
        }
    }
    
    string BuildCaveName(int caveNum)
    {
        string name = (GetLetterFromNumber(caveNum / (26 * 26)) + GetLetterFromNumber((caveNum / 26) % 26) + GetLetterFromNumber(caveNum % 26)).TrimStart('a');
        if (name == "")
            name = "a";
        return name;
    }
    
    string GetLetterFromNumber(int num)
    {
        return "" + (char)('a' + num);
    }