【问题标题】:Generating combination of letters生成字母组合
【发布时间】:2010-07-02 23:38:38
【问题描述】:

给定一组字母,例如来自 A.. F,如何生成这些字母的特定长度组合。即对于长度 4,生成包含这些字母 {AAAA, ABCD, ...} 的所有字符串(包括重复项)。我无法理解如何编写代码。这与我试图模拟的 Mastermind 游戏有关。是否有任何算法来执行这一代。

问候,
小黑子

【问题讨论】:

  • 嗯,先想想吧。您将如何生成所有长度为 1 的字符串?那么你将如何生成所有长度为 2 的字符串?现在概括一下。
  • bruteforce: for c1 in ('A'...'Z') : for c2 in ('A' to 'Z') ....combo=c1+c2...

标签: generator


【解决方案1】:

有一种称为堆算法的算法用于生成排列。这可能适合您的目的。我找到了一个示例实现here

【讨论】:

    【解决方案2】:

    我不确定这种算法的名称是什么,但它是一种递归算法。也就是说,有一种方法可以计算出一个字符,然后简单地继续调用自身,直到达到所需的字符串长度,然后开始填充数组。下面是一些可以提供帮助的示例 C# 代码:

        public void GetPermutations()
        {
            string currentPrefix = ""; // Just a starting point
            int currentLength = 1; // one-based
            int desiredLength = 4; // one-based
            string alphabet = "ABCDEF"; // Characters to build permutations from
            List<string> permutations = new List<string>();
    
            FillPermutations(currentPrefix, currentLength, alphabet, desiredLength, permutations);
        }
    
        public void FillPermutations(string currentPrefix, int currentLength, string alphabet, int desiredLength, List<string> permutations)
        {
            // If we're not at the desired depth yet, keep calling this function recursively
            // until we attain what we want.
            for (int i = 0; i < alphabet.Length; i++)
            {
                string currentPermutation = currentPrefix + alphabet[i].ToString();
    
                if (currentLength < desiredLength)
                {
                    // Increase current length by one and recurse.  Current permutation becomes new prefix
                    int newCurrentLength = currentLength + 1;
                    FillPermutations(currentPermutation, newCurrentLength, alphabet, desiredLength, permutations);
                }
                else
                {
                    // We're at the desired length, so add this permutation to the list
                    permutations.Add(currentPermutation);
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多