0

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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
bdg
  • 465
  • 6
  • 18
  • 1
    As commonly seen in Excel? There are quirks to that counting system. – Damien_The_Unbeliever Nov 26 '18 at 10:40
  • If you want it based on a number, take a look at [this answer](https://stackoverflow.com/a/2954999/3181933) for converting an integer to binary. All you need to do is change it to be based on 26 characters of the alphabet rather than 2 (0 and 1) characters. – ProgrammingLlama Nov 26 '18 at 10:40
  • Also,note that a simple substitution of 10 digits with the first 10 characters of the alphabet is a far simpler way of being able to represent one of 1000 items in 3 characters. – Damien_The_Unbeliever Nov 26 '18 at 10:42
  • Lots of answers for this scheme here: https://stackoverflow.com/questions/181596/how-to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa – Rup Nov 26 '18 at 10:43
  • Do you want to go from "a" to "zzz" or actually from "aaa" to "zzz"? – Thomas Hilbert Nov 26 '18 at 10:59
  • @ThomasHilbert it would be from "a" to "zzz" or equivalent of 1000 characters – bdg Nov 26 '18 at 11:14
  • All right. But be aware though that 3 columns of lower-case letters amount to 17576 possible values, not 1000. Up to 676 cave names can be expressed in 2 columns of lowercase letters. – Thomas Hilbert Nov 26 '18 at 11:25

2 Answers2

1

It's like a converter for excel columns : How to convert a column number (eg. 127) into an excel column (eg. AA)

private string GetExcelColumnName(int columnNumber)
{
    int dividend = columnNumber;
    string columnName = String.Empty;
    int modulo;

    while (dividend > 0)
    {
        modulo = (dividend - 1) % 26;
        columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
        dividend = (int)((dividend - modulo) / 26);
    } 

    return columnName;
}
Julien
  • 3,509
  • 20
  • 35
1
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);
}
Thomas Hilbert
  • 3,559
  • 2
  • 13
  • 33