c# - 不重复的单词组合

标签 c# string combinations words

我有10个字。如何获得 5 个单词的所有可能组合 (n=10, k=5)。顺序无关紧要

例如:“A”、“B”、“C”,如果 k=2(本例中为 n=3),则需要 AB、BC 和 AC。也许您知道一些有用的代码或示例。

附言对不起,如果我不够正确,因为我的英语不太好。

最佳答案

您要做的是获取集合的所有排列。

这是代码片段:

static void Main(string[] args)
{
    var list = new List<string> { "a", "b", "c", "d", "e" };
    var result = GetPermutations(list, 3);
    foreach (var perm in result)
    {
        foreach (var c in perm)
        {
            Console.Write(c + " ");
        }
        Console.WriteLine();
    }
    Console.ReadKey();
}

static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> items, int count)
{
    int i = 0;
    foreach (var item in items)
    {
        if (count == 1)
            yield return new T[] { item };
        else
        {
            foreach (var result in GetPermutations(items.Skip(i + 1), count - 1))
                yield return new T[] { item }.Concat(result);
        }

        ++i;
    }
}

输出:

a b c 
a b d 
a b e 
a c d 
a c e 
a d e 
b c d 
b c e 
b d e 
c d e 

关于c# - 不重复的单词组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5132758/

相关文章:

c# - 在 for/foreach 循环中声明相同的对象

arrays - Swift:检测字符串的首字母何时不等于特定字符?

list - 给定长度的列表组合后跟 Prolog 中的排列?

python - 提取开始标记和结束标记之间的所有字符串

C++一组字符串的所有排列

algorithm - 是否有解决组合的通用模式?

c# - 如何从同一应用程序的两个实例安全地写入日志文件?

c# - 将具有 2 "left Join"和多个条件的 Sql 查询转换为 Entity Framework 查询

c# - 使用MediaPlayer播放WAV文件

java - 如何从图像转换为短字符串?