Archived
backup
This commit is contained in:
@@ -14,7 +14,8 @@ namespace XericLibrary.Runtime.MacroLibrary
|
||||
#region 洗牌算法
|
||||
|
||||
/// <summary>
|
||||
/// Fisher-Yates洗牌算法,时间复杂度为O(n*n),空间复杂度为O(n)
|
||||
/// Fisher-Yates洗牌算法,时间复杂度为O(n*n),空间复杂度为O(n);
|
||||
/// 缺点是元素0很大概率会在最后出现
|
||||
/// </summary>
|
||||
/// <param name="length">待选项目的索引长度</param>
|
||||
/// <param name="select">输出项目的索引长度</param>
|
||||
@@ -39,6 +40,44 @@ namespace XericLibrary.Runtime.MacroLibrary
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 重复的洗牌
|
||||
/// </summary>
|
||||
/// <param name="length"></param>
|
||||
/// <param name="select"></param>
|
||||
/// <param name="repet"></param>
|
||||
/// <returns></returns>
|
||||
public static List<int> FisherYatesShuffle(int length, int select, int repet)
|
||||
{
|
||||
if(select > length)
|
||||
throw new ArgumentOutOfRangeException("在进行洗牌时,要求输出的项目比拥有的项目更多,这是不合理的。");
|
||||
#if UNITY_EDITOR
|
||||
if(repet > 100)
|
||||
Debug.LogError("洗牌的重复次数太高(> 100),已限制数量");
|
||||
#endif
|
||||
repet = Math.Clamp(repet, 1, 100);
|
||||
|
||||
var random = new System.Random();
|
||||
|
||||
List<int> arr = Enumerable.Range(0, length).ToList();
|
||||
List<int> res = new List<int>();
|
||||
|
||||
for(int j = 0; j < repet; j++)
|
||||
{
|
||||
for(int i = 0; i < length; i++)
|
||||
{
|
||||
int k = random.Next(arr.Count);
|
||||
res.Add(arr[k]);
|
||||
arr.RemoveAt(k);
|
||||
}
|
||||
arr = res.ToList();
|
||||
res.Clear();
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 蓄水池抽样算法,可以在线程安全的情况下完成洗牌。
|
||||
/// </summary>
|
||||
|
||||
Reference in New Issue
Block a user