Here, we take array ["A","B","C","D"] as an example. Two elements are extracted from it for combination. As we all know, the fundamental difference between combination and arrangement is whether the relationship is sorted. On the above array
Permutation, in fact, is a process in which the first element is combined with the other three elements, the second element is combined with the remaining two elements, the third element is combined with the remaining one, and finally the whole combination process is completed.
The specific combination code is as follows:
/// <summary> ///<! [CDATA [combo]] > /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="m"></param> /// <returns></returns> static List<T[]> GetCombination<T>(T[] source, int m) { var list = new List<T[]>(); int[] indexs = new int[m]; GetCombination<T>(ref list, source, indexs, 0, m, m); return list; } /// <summary> /// /// </summary> ///< typeparam name = "t" > ///< param name = "list" > ///< param name = "source" > ///< param name = "indexes" > ///< param name = "start" > ///< param name = "m" > ///< param name = "meindex" > static void GetCombination<T>(ref List<T[]> list, T[] source, int[] indexs, int start, int m, int mIndex) { for (var i = start; i < source.Length; i++) { indexs[mIndex - 1] = i; if (mIndex > 1) { GetCombination(ref list, source, indexs, i + 1, m, mIndex - 1);//recursion } else { T[] arrayCombination = new T[m];//Store a set of combinations for (var j = 0; j < indexs.Length; j++) { arrayCombination[j] = source[indexs[j]]; } Array.Sort(arrayCombination);//Sorted, can be deleted list.Add(arrayCombination); } } }
Our console call performs the following:
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { var array = new string[] { "A", "B", "C", "D" }; var r = GetCombination<string>(array, 2); foreach (var item in r) { Console.WriteLine(string.Join("", item)); } Console.ReadLine(); }
Output results:
This completes a composite demo about C ා.