版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27032631/article/details/78054929
这里涉及到了一个数学知识点:组合
得到一个组合的所有可能,然后将各个可能列出 ,这里就要用到交叉数组了
(开始的思路是 创建一个二维数组,以排序可能作为行,取几个元素为列,当开发过程中发现,C++和Java可以直接取得二维的每一行当做数组使用,C#不行(此处可能描述不当)。庆幸的是C#存在交叉数组
,这样就解决了我的问题,将每一种可能当做数组的行,一行行显示,代码如下)
using System;
namespace ConsoleApplication4
{
public class CombineAlgorithm
{
static int objLineIndex = 0;
static int[][] obj;
//数学组合C 共有多少种排序可能
public static int combination(int m, int n)
{
if (m < n)
return 0;
int k = 1;
int j = 1;
for (int i = n; i >= 1; i--)
{
k = k * m;
j = j * n;
m--;
n--;
}
return k / j;
}
//以排序可能作为交叉数组的索引 每一种的数组值作为集合
public static void combine(int[] src, int srcIndex, int i, int n, int[] temp)
{
int j;
for (j = srcIndex; j < src.Length - (n - 1); j++)
{
temp[i] = src[j];
if (n == 1)
{
Array.Copy(temp, 0, obj[objLineIndex], 0, temp.Length);
objLineIndex++;
}
else
{
n--;
i++;
combine(src, j + 1, i, n, temp);
n++;
i--;
}
}
}
public static void Main(string[] args)
{
int[] cards = new int[] { 2,3,5,13,31,43,21,32,34,37,49,46,29};
Array.Sort(cards);
int m = cards.Length,n=5;
obj = new int[combination(m,n)][];
for (int i = 0; i < obj.Length; i++)
{
obj[i] = new int[5];
}
int[] temp = new int[n];
combine(cards, 0, 0, n, temp);
foreach (int[] child in obj)
{
foreach (int i in child)
{
Console.Write(i+" ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}