c# - 生成一系列递归字母(如 Excel 列标题)

标签 c# recursion f#

长话短说,我正在尝试创建某种国际象棋库,它可能适用于任何大小的棋盘,最大可能是 int.MaxValue by int.MaxValue。生成无限的排名数字列表很容易:

    static IEnumerable<int> GetRankNumbers()
    {
        for(int i = 1; ; i++)
            yield return i;
    }

但是为了生成文件字母,我目前正在这样做:

    static IEnumerable<string> GetFileLetters()
    {
        const string theLetters = "abcdefghjklmnopqrstuvwxyz"; // there is no 'i'.

        for(int i = 0; ; i++)
        {
            var factor = i / theLetters.Length;
            var index = i % theLetters.Length;

            var sb = new StringBuilder();
            sb.Append(theLetters[index]);

            for(int j = 0; j < factor; j++)
            {
                sb.Append(theLetters[index]);
            }

            yield return sb.ToString();
        }
    }

产生以下内容:

var x = GetFileLetters().Take(100);
foreach(var item in x) Write(item + " ");

Output:
a b c d e f g h j k l m n o p q r s t u v w x y z aa bb cc dd ee ff gg hh jj kk ll mm nn oo pp qq rr ss tt uu vv ww xx yy zz aaa bbb ccc ddd eee fff ggg hhh jjj kkk lll mmm nnn ooo ppp qqq rrr sss ttt uuu vvv www xxx yyy zzz aaaa bbbb cccc dddd eeee ffff gggg hhhh jjjj kkkk llll mmmm nnnn oooo pppp qqqq rrrr ssss tttt uuuu vvvv wwww xxxx yyyy zzzz 

如您所见,仅 100 件元素,它就会迅速膨胀。我怎样才能让它返回 a, b, c, ..., z, aa, ab, ac, ... , az, ba, bb, .. etc 的结果?

额外的问题:如何在 F# 中执行此操作?

附言。我发现了一些类似的问题here , here , 和 here ,但他们都没有像我尝试的那样使用 IEnumerableyield return 和理论上无限的集合来做到这一点。最后一个有点作弊(想想我真的不需要更多..但我这样做是为了学习)。

最佳答案

首先,让我们构造一个函数来生成一系列 n 字符组合。对于 n=1(基本情况),它将只生成一个字符序列。对于 n=2,它将产生 2 个字符的所有组合。等等。

对于给定的 n , 我们如何产生 n 的所有组合人物?首先,我们在 n-1 的所有组合前加上“a”字符,然后我们在 n-1 的所有组合前面加上“b”字符等:

let rec seqOfNChars n = 
  seq {
    for c in ['a' .. 'z'] do
      for s in seqOfNChars (n-1) do
        yield sprints "%c%s" c s
  }

然后添加基本情况:

let rec seqOfNChars n = 
  seq {
    for c in ['a' .. 'z'] do
      if n <= 1 then
        yield string c
      else
        for s in seqOfNChars (n-1) do
          yield sprintf "%c%s" c s
  }

既然我们有了这个函数,我们就可以很容易地产生一个所有长度的所有组合的序列,从 1 开始:

let allHeaders = Seq.initInfinite ((+) 1) |> Seq.collect seqOfNChars

关于c# - 生成一系列递归字母(如 Excel 列标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900172/

相关文章:

java - 使用 "visited"集进行递归优化,用于纯函数

javascript - 基于另一个对象递归更新特定键的嵌套对象值

c# - .net core AspnetCore Razor View 因 CompilationFailedException 而失败

c# - 删除匿名事件处理程序

c# - Coldfusion OpenXml 错误 : Could not load file or assembly 'DocumentFormat.OpenXml'

c# - 使用 CodeDom 指定类型别名

python - 可以用递归完成吗?

f# - F# 和 OCaml 等函数式语言中的 "let"关键字有什么用?

c# - F# 轻量级脚本环境

f# - 模式匹配,F# 与 Erlang