class Program
{
//采用递归的方式进行实现组合
static IEnumerable<IEnumerable<T>>
GetCombinations<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });//递归出口
//因为组合是没有排列顺序的,因此只从比当前序列随后一个元素后面的序列集中抽取元素
return GetCombinations(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
//采用递归算法实现排序
static IEnumerable<IEnumerable<T>>
GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });//递归排序的出口
//利用linq的selectMany方法将两个序列进行组合
return GetPermutations(list, length - 1)
.SelectMany(t => list.Where(o => !t.Contains(o)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
static void Main(string[] args)
{
int countP = 0, countC = 0;
const int k = 5;
//为了实现排列所属的输出需要对结合进行升序排序
var n = new[] { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35};
Console.WriteLine("排列");
Console.WriteLine("===============================");
foreach (IEnumerable<int> i in GetPermutations(n, k))
{
Console.WriteLine(string.Join(" ", i));
countC++;
}
Console.WriteLine("排序总数: " + countC);
Console.WriteLine();
Console.WriteLine("===============================");
Console.WriteLine("组合");
Console.WriteLine("===============================");
foreach (IEnumerable<int> i in GetCombinations(n, k))
{
Console.WriteLine(string.Join(" ", i));
countP++;
}
Console.WriteLine("组合的总数 : " + countP);
}
}
C#实现排列和组合,打印排列和组合的总数以及集中的各种组合方式
最新推荐文章于 2023-03-31 10:51:39 发布