C#计算来自任意数量列的单词组合

时间:2016-05-12 11:32:45

标签: c# combinations permutation

对于单个数组或数组向量有很多组合解决方案,您需要每个可能的排列,但我需要稍微不同的解决方案。我曾尝试过将碎片拼凑在一起但却再也看不到树木了。

我需要一个解决方案,它将采用一个csv文件,其中包含最多50列和每列任意数量的单词行。每列的行数可以不同。

我需要做的是获取此输入,然后依次遍历每一列,选择一个单词以创建每个可能的行组合,跳过任何空行的行/列。嵌套循环会对预设数量的列执行此操作,但随着列的更改,这是一个问题。编程很新。希望它缺少一个相当简单的逻辑概念。

例如:

输入:
熊,爪,甜甜圈 鸡肉,沙拉,
金枪鱼色拉,,

输出:
熊,爪,甜甜圈 熊,沙拉,甜甜圈 熊,沙拉
鸡,爪,甜甜圈 鸡肉,沙拉,甜甜圈 鸡,爪 鸡肉,沙拉 鸡肉,沙拉,甜甜圈 ...
金枪鱼,爪子,沙拉 金枪鱼沙拉 等

1 个答案:

答案 0 :(得分:0)

我在Andrew的同时写了一个答案,但不久之后,要求变得不清楚,所以我没有发布它。现在他们已经清楚了,这是一个使用IEnumerable s的替代方案。它也不需要Array.Reverse()每个答案。

原始答案文字

您希望以递归方式解决此问题。

以下代码假定您已将CSV解析为某IEnumerableIEnumerable个。

static void Main()
{
    var wordLists = new List<string[]>()
    {
        new string[] { "bear", "chicken", "tuna" },
        new string[] { "claw", null, "salad" },
        null,
        new string[] { "donut", "salad", null },
    };

    foreach (var result in AllPermutations(wordLists)) 
    {
        System.Console.WriteLine(string.Join(",", result));
    }
}

// our recursive function. 
private static IEnumerable<IEnumerable<string>> AllPermutations(IEnumerable<IEnumerable<string>> wordLists, int index = 0, List<string> current = null)
{
    if (current == null) 
    {
        current = new List<string>();
    }

    if (index == wordLists.Count()) 
    { // the end condtion. it is reached when we are past the last list
        yield return current;
    }
    else
    { // if we are not at the end yet, loop through the entire list
      // of words, appending each one, then recursively combining
      // the other lists, and finally removing the word again.
        var wordList = wordLists.ElementAt(index);
        if (wordList != null)
        {
            foreach (var word in wordList)
            {
                if (word == null) continue;
                current.Add(word);
                foreach (var result in AllPermutations(wordLists, index + 1, current)) 
                {
                    yield return result;
                }
                current.RemoveAt(current.Count - 1);
            }
        }
        else
        {
            foreach (var result in AllPermutations(wordLists, index + 1, current)) 
            {
                yield return result;
            }
        }
    }
}

请注意,对于50列,可能会有很多组合非常快