How to use LINQ to find all combinations of n items from a set of numbers?(如何使用 LINQ 从一组数字中查找 n 项的所有组合?)
问题描述
我正在尝试编写一个算法来从一组数字中选择 n 个值的所有组合.
I'm trying to write an algorithm to select all combinations of n values from a set of numbers.
例如,给定集合:1, 2, 3, 7, 8, 9
集合中 2 个值的所有组合是:
All combinations of 2 values from the set is:
(1, 2), (1, 3), (1, 7), (1, 8), (1, 9), (2, 3), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (7, 8), (7, 9), (8, 9)
(1, 2), (1, 3), (1, 7), (1, 8), (1, 9), (2, 3), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (7, 8), (7, 9), (8, 9)
而 3 是:
(1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 7, 8), (3, 7, 9), (3,8, 9), (7, 8, 9)
(1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 7, 8), (3, 7, 9), (3, 8, 9), (7, 8, 9)
等等!
我目前正在使用方法来产生 2、3 和 4 值组合的返回集,但在我看来,这可以在 LINQ 查询中概括.
I'm currently using methods to to yield return sets of combinations of 2, 3 and 4 values, but it seems to me this could be generalised in a LINQ query.
感谢您的帮助!
推荐答案
用法:
var results = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);
代码:
public static class Ex
{
public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] {e}).Concat(c)));
}
}
这篇关于如何使用 LINQ 从一组数字中查找 n 项的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 LINQ 从一组数字中查找 n 项的所有组合?


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01