Incrementing alphabets

假如想象 提交于 2019-11-29 10:56:09

Any recursive function can be converted into an equivalent iterative one. I find it always easy to think recursively first:

static string GetColumnName(int index)
{
    const int alphabetsCount = 26;

    if (index > alphabetsCount) {
        return GetColumnName(index / alphabetsCount) + GetColumnName(index % alphabetsCount);
    } else {
        int code = (index - 1) + (int)'A';
        return char.ConvertFromUtf32(code);
    }
}

Which can be simple converted into:

static string GetColumnName(int index)
{
    const int alphabetsCount = 26;
    string result = string.Empty;

    while (index > 0) {
        result = char.ConvertFromUtf32(64 + (index % alphabetsCount)) + result;
        index /= alphabetsCount;
    }

    return result;
}

Even so, listen to Joel.

Joel Coehoorn

See this question:
Translate a column index into an Excel Column Name

or this one:
How to convert a column number (eg. 127) into an excel column (eg. AA)

Though the first link has a correct answer right at the top and the 2nd has several that are not correct.

Recursion is one possibility -- if index > 26, you deal with index % 26 in this call and concatenate it to a recursive call on index / 26. However, iteration is often speedier and not hard to arrange for simple cases such as this one. In pseudocode:

string result = <convert `index % 26`>
while index > 26:
  index = index / 26
  result = <convert `index % 26`> + result
return result

or the like.

static string GetColumnName(int index)
{
    const int alphabetsCount = 26;
    string result = '';

    if (index >= alphabetsCount)
    {
        result += GetColumnName(index-alphabetsCount)
    }
    return (string) (64 + index);
}

My C# is HORRIBLE AND RUSTY. Interpret this as pseudocode - it will almost certainly not compile, but may get you started.

I don't want to answer the question in C# but I'm going to show you how easy this is in Haskell.

alphas :: [String]
alphas = [x ++ [c] | x <- ([]:alphas), c <- ['A'..'Z']]

Prelude> take 100 alphas
["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T",
 "U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK",
 "AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA",
 "BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ",
 "BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG",
 "CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV"]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!