Fisher-Yates Shuffle算法
1.创建一个新的list
2.随机取出当前0-list.Count其中一个数
3.把老list当前随机数位置添加到新list
4.老list删除这个数
5.直到老list.Count=0结束返回
public void FisherYatesShuffle<T>(List<T> list)
{
List<T> cache = new List<T>();
int currentIndex;
while (list.Count > 0)
{
currentIndex = Random.Range(0, list.Count);
cache.Add(list[currentIndex]);
list.RemoveAt(currentIndex);
}
for (int i = 0; i < cache.Count; i++)
{
list.Add(cache[i]);
}
}
随机性 可验证每一个数的概率都是相等的
一个元素m被放入第i个位置的概率P = 前i-1个位置选择元素时没有选中m的概率 * 第i个位置选中m的概率
时间复杂度为O(n^2)空间复杂度为O(n)
Knuth-Durstenfeld Shuffle算法
是上面板的升级版本 不用new新的list 在原list进行交换
1.随机取出当前0-list.Count-i的数(就是相当于不移除,要从后每次遍历都要从后往前空出一个位置给随机完的数交换到(最后一个-i)这个位置)
比如一共1234
你在前四个随机一个2 2和4交换 成了1432
然后在前三个随机 只能随机到143其中一个
就按3来说 他和自己交换就是位置不变 成了1432
然后在前两个交换 比如随机了一个1 和4交换 成了4132
最后一个不交换不然会数组越界
2.把当前随机的数和最后空出来的数交换
这样可以确保不会重复随机
public void KnuthDurstenfeldShuffle<T>(List<T> list)
{
//随机交换
int currentIndex;
T tempValue;
for (int i = 0; i < list.Count; i++)
{
currentIndex = Random.Range(0, list.Count - i);
tempValue = list[currentIndex];
list[currentIndex] = list[list.Count - 1 - i];
list[list.Count - 1 - i] = tempValue;
}
}
然后用forr优化 因为for循环每次都获取list.count比较 而forr是反向 只用获取一次
不过有局限因为只有开始获取了长度而不是每次获取 导致必须一开始知道长度 长度未知的话只能用第一种
public void KnuthDurstenfeldShuffle<T>(List<T> list)
{
//随机交换
int currentIndex;
T tempValue;
for (int i = list.Count - 1; i >= 0; i--)
{
currentIndex = Random.Range(0, i+1);
tempValue = list[currentIndex];
list[currentIndex] = list[i];
list[i] = tempValue;
}
}
随机性
也是相等的
时间复杂度为O(n)空间复杂度为O(1)
是最佳的洗牌算法
Inside-Out Algorithm算法
上面算法是内部打乱算法 如果我们想保留数据需要另外开辟一个List保存 我觉得跟上面的差不多就用个list保存 数组是struct可以直接赋值时间复杂度可能是O(n)
public List<T> InsideOutAlgorithm<T>(List<T> list)
{
List<T> cache = new List<T>();
for (int i = 0; i < list.Count; i++)
{
cache.Add(list[i]);
}
//随机交换
int currentIndex;
T tempValue;
for (int i = cache.Count - 1; i >= 0; i--)
{
currentIndex = Random.Range(0, i + 1);
tempValue = cache[currentIndex];
cache[currentIndex] = cache[i];
cache[i] = tempValue;
}
return cache;
}
时间复杂度为O(n^2)空间复杂度为O(n)
ReservoirSampling蓄水池抽样算法
如果我们想从一个从N个元素中随机的抽取k个元素,其中N无法确定 就要用到这个算法
其实还有一种算法一开始会想到等概率抽取法,每次在(0,n-1)随机一个数,随机m次如果有相同的重新随机。如果N较大也可能不确定大小就只能用蓄水池抽样了
1.先把读到的前k个对象放入“水库”
2.对于第k+1个对象开始,以k/(k+1)的概率选择该对象,以k/(k+2)的概率选择第k+2个对象,以此类推,以k/m的概率选择第m个对象(m>k)。
3.如果m被选中,则随机替换水库中的一个对象。最终每个对象被选中的概率均为k/n,证明如下。
第m个对象被选中的概率=选择m的概率(其后元素不被选择的概率+其后元素被选择的概率不替换第m个对象的概率)
每个元素被抽中概率相等
public List<T> ReservoirSampling<T>(List<T> list, int m)
{
List<T> cache = new List<T>(m);
for (int i = 0; i < m; i++)
{
cache.Add(list[i]);
}
int currentIndex;
for (int i = m; i < list.Count; i++)
{
currentIndex = Random.Range(0, i + 1);
if (currentIndex < m)
{
cache[currentIndex] = list[i];
}
}
return cache;
}