生成字母组合

时间:2010-07-02 23:38:38

标签: generator

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

的问候,
darkie

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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);
            }
        }
    }