C#实现排列和组合,打印排列和组合的总数以及集中的各种组合方式

  class Program{//采用递归的方式进行实现组合static IEnumerable>GetCombinations(IEnumerable 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>GetPermutations(IEnumerable 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 i in GetPermutations(n, k)){Console.WriteLine(string.Join(" ", i));countC++;}Console.WriteLine("排序总数: " + countC);Console.WriteLine();Console.WriteLine("===============================");Console.WriteLine("组合");Console.WriteLine("===============================");foreach (IEnumerable i in GetCombinations(n, k)){Console.WriteLine(string.Join(" ", i));countP++;}Console.WriteLine("组合的总数 : " + countP);}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部