2010-07-02 167 views
0

给定一组字母,从A .. F中说出,如何为特定长度生成这些字母的组合。即长度为4,生成包含这些字母的所有字符串{AAAA,ABCD,...}(包括重复项)。我无法理解如何使用代码来完成它。这与我试图模拟的Mastermind游戏有关。有没有任何算法来执行这一代。生成字母组合

问候,
darkie

+2

那么,首先考虑一下。你将如何产生长度为1的所有字符串?那么你将如何产生长度为2的所有字符串?现在推广它。 – BobbyShaftoe 2010-07-02 23:47:55

+0

bruteforce:对于c1('A'...'Z'):对于c2('A'到'Z').... combo = c1 + c2 ... – 2010-07-02 23:59:06

回答

1

我不确定这个算法的名字是什么,但它是递归的。也就是说,有一个方法可以计算出一个字符,并且直接调用自己,直到达到所需的字符串长度,然后开始填充数组。这里有一些示例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); 
      } 
     } 
    } 
+0

非常感谢。这给了我一个清晰的想法! – 2010-07-03 01:20:40

2

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