1. 获取数组的全排列 ( Permutation )
public static void FullArrange(List array, int begin, int end, System.Action > call) { if(begin == end) { call.Invoke(array.AsReadOnly()); } else { for(int i = begin; i <= end; i++) { Swap(array, begin, i); FullArrange(array, begin + 1, end, call); Swap(array, begin, i); } } } private static void Swap (List lsArray, int x, int y) { var t = lsArray[x]; lsArray[x] = lsArray[y]; lsArray[y] = t; }
var list = new List<int>() { 1, 2, 3 }; FullArrange(list, 0, list.Count - 1, (_array) => { string info = ""; foreach(var data in _array) { info += data + ","; } Debug.Log(info); });
2. 数组的全概率排列 ( 每个位都能选择数组中所有数 )
public static void Probability(T[] array, int count, System.Action call) { foreach(var data in array) { Probability(array, 0, count, null, data, call); } } private static void Probability (T[] array, int index, int count, T[] container, T value, System.Action call) { if(container == null) { container = new T[count]; } container[index] = value; if(index == count - 1) { var newC = new T[count]; System.Array.Copy(container, newC, count); call.Invoke(newC); } else { index++; foreach(var data in array) { var newC = new T[count]; System.Array.Copy(container, newC, index); Probability(array, index, count, newC, data, call); } } }
string[] bb = new string[5] { "+", "-", "x", "/", "%" }; Probability(bb, 3, (_array) => { var str = string.Join(",", _array); Debug.Log(str); });
2.1 不需要额外产生数组的版本
public static void Probability2(T[] array, int count, System.Action call) { var tempArray = new T[count]; foreach(var data in array) { Probability2(array, 0, count, tempArray, data, call); } } private static void Probability2 (T[] array, int index, int count, T[] container, T value, System.Action call) { if(container == null) { container = new T[count]; } container[index] = value; if(index == count - 1) { call.Invoke(container); } else { index++; foreach(var data in array) { Probability(array, index, count, container, data, call); } } }
string[] bb = new string[5] { "+", "-", "x", "/", "%" }; Probability2(bb, 3, (_array) => { var str = string.Join(",", _array); Debug.Log(str); });