我想得到从36个数中取18个数的全部组合,这个组合有上亿种。
我采用递归计算,但是效率太低,运行时CPU和内存利用率不高,耗时太长,恳请高人赐教。
是否有多线程或其他更高效的算法取数。
/// <param name="currentIndex">当前数组索引</param>
/// <param name="remain">需取的个数</param>
/// <param name="currentSelect">生成当前组合的字符串集合</param>
/// <param name="Items">M个数集合</param>
static void comb(int currentIndex, int remain, string currentSelect, string[] Items)
{
if (remain == 0)
{
//当此行不需取数时,列出此行取的N个数
strResult += currentSelect + ";";
return;
}
if (Items.Length - currentIndex < remain)
return;
//递归取数
comb(currentIndex + 1, remain - 1, currentSelect + "," + Items[currentIndex], Items);
comb(currentIndex + 1, remain, currentSelect, Items);
}
static void Main(string[] args) { for (int i = 0; i < Items.Length; i++) { System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(DoWork)); t.Start(i); } //System.Threading.Thread.Sleep(10000); Console.Write(strResult.Length); Console.ReadLine(); } static string[] Items = new string[] { "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","36"}; static void DoWork(object o) { comb(int.Parse(o.ToString()), 18, "", Items); } static string strResult = ""; /// <param name="currentIndex">当前数组索引</param> /// <param name="remain">需取的个数</param> /// <param name="currentSelect">生成当前组合的字符串集合</param> /// <param name="Items">M个数集合</param> static void comb(int currentIndex, int remain, string currentSelect, string[] Items) { if (Items.Length - currentIndex < remain) return; if (remain == 0) { //当此行不需取数时,列出此行取的N个数 strResult += currentSelect + ";"; return; } //递归取数 comb(currentIndex + 1, remain - 1, currentSelect + "," + Items[currentIndex], Items); }
我换了一下多线程,不过还是很慢,
算法我感觉没有什么可优化的了,只能使用枚举的方式,便利所有可能,
从36个数中取18个数的全部组合,这个组合不止上亿种,
36的18次方等于 1.031442479849054e+28
一个28位的数字,即使每秒千亿次的计算,也会需要很长时间,不知道你这个算法需要用到什么应用上呢.?
希望能帮到你!!
你好,算法确实没有什么可优化了,不过多线程可以稍微提高CPU的利用率(我还想.NET有没有其他机制可以提高运算效率)
这个算法是我业余爱好,研究彩票概率很感谢你的回复。
这是个无解的问题,hash是否有用?
http://bbs.csdn.net/topics/300190422