组合算法
自交非杂交
指定数组: {"A","B","C","D"}
指定相交次数:3
输出:
AAA AAB AAC AAD ABA ABB ABC ABD...DDA DDB DDC DDD
直接上代码:
/// <summary> /// 组合算法 /// </summary> /// <param name="word">需要组合的字符数组:{"A","B","C","D"}</param> /// <param name="num">组合的次数</param> /// <returns>组合结果集</returns> static List<string> Combination(string[] word, int num) { /*结果集*/ List<string> result = new List<string>(); /*把字符数字放入队列*/ Queue<string> _wordque = new Queue<string>(); foreach (var w in word) _wordque.Enqueue(w); /*字符数组总长度*/ var len = word.Length; /*字符数组存在的组合总数*/ var sum = int.Parse(Math.Pow(len, num).ToString()); /*第一次分片个数*/ var overlap = sum / len; /*次序*/ var rank = 0; /* * 设需要生成3位长度字符组合,则{"A","B","C","D"}数组共有64中组合方式 * 第1个字符第一次分片:16(A)+16(B)+16(C)+16(D),即所有组合只会出现A B C D四种开头,那么每种开头存在16中组合 * 第2个字符第二次分片:4(AA)+4(AB)+4(AC)+4(AD)+...+4(DA)+4(DB)+4(DC)+4(DD),在1基础上所有组合只会出现AA?,AB?,AC?,AD?...DA?,DB?,DC?,DD?的组合方式 * 第3个字符第三次分片:1(AAA+AAB+AAC+AAD+ABA+ABC+...+DDA+DDB+DDC+DDD),在2基础上所有组合只会出现AA+(ABCD)组合方式 * 64->16->4->1组合法 * 说明:以上只是针对测试用例的数值解释,当输入的num不是3的时候,将改变对应的数值 * */ while (overlap >= 1) { if (!result.Any()) { /*1.组合:取第一个字符*/ for (var j = 0; j < len; j++) { /*出队,分配给第一片的result集合*/ var _word = _wordque.Dequeue(); for (var i = 0; i < overlap; i++) result.Add(_word); /*归队*/ _wordque.Enqueue(_word); } } else { /*2.组合:依次取后续字符*/ /*取最后一个字符判断*/ var count = overlap == 1 ? len : overlap; count = int.Parse((Math.Pow(count, rank) * len).ToString()); for (var i = 0; i < count; i++) { var start = i * overlap; if (start >= result.Count()) break; var end = start + overlap; var _word = _wordque.Dequeue(); for (int j = start; j < end; j++) { result[j] = result[j] + _word; } _wordque.Enqueue(_word); } } overlap = overlap / len; rank++; } return result; }
时间: 2024-11-10 07:06:39