实用小算法合集
1. 获取数组的全排列 ( Permutation )
public static void FullArrange<T>(List<T> array, int begin, int end, System.Action<System.Collections.ObjectModel.ReadOnlyCollection<T>> 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<T>(List<T> 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>(T[] array, int count, System.Action<T[]> call) { foreach(var data in array) { Probability(array, 0, count, null, data, call); } } private static void Probability<T>(T[] array, int index, int count, T[] container, T value, System.Action<T[]> 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>(T[] array, int count, System.Action<T[]> call) { var tempArray = new T[count]; foreach(var data in array) { Probability2(array, 0, count, tempArray, data, call); } } private static void Probability2<T>(T[] array, int index, int count, T[] container, T value, System.Action<T[]> 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); });
------------------- Unity3D -------------------
1. 测试渲染是否在相机内的方法, 比系统自带的 OnBecameInvisible 更靠谱, OnBecameInvisible 基本没有用...
public static bool IsVisible(Renderer renderer, Camera camera) { Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera ?? Camera.main); return GeometryUtility.TestPlanesAABB(planes, renderer.bounds); }