带权重的随机:
/// <summary>
/// 带权重的随机
/// </summary>
/// <param name="list">原始列表</param>
/// <param name="count">随机抽取条数</param>
/// <returns></returns>
public static List<T> GetRandomList<T>(List<T> list, int count) where T : RandomObject
{
if (list == null || list.Count <= count || count <= 0)
{
return list;
}
//计算权重总和
int totalWeights = 0;
for (int i = 0; i < list.Count; i++)
{
totalWeights += list[i].Weight + 1; //权重+1,防止为0情况。
}
//随机赋值权重
System.Random ran = new System.Random(GetRandomSeed()); //GetRandomSeed()随机种子,防止快速频繁调用导致随机一样的问题
List<KeyValuePair<int, int>> wlist = new List<KeyValuePair<int, int>>(); //第一个int为list下标索引、第一个int为权重排序值
for (int i = 0; i < list.Count; i++)
{
int w = (list[i].Weight + 1) + ran.Next(0, totalWeights); // (权重+1) + 从0到(总权重-1)的随机数
wlist.Add(new KeyValuePair<int, int>(i, w));
}
//排序
wlist.Sort(
delegate (KeyValuePair<int, int> kvp1, KeyValuePair<int, int> kvp2)
{
return kvp2.Value - kvp1.Value;
});
//根据实际情况取排在最前面的几个
List<T> newList = new List<T>();
for (int i = 0; i < count; i++)
{
T entiy = list[wlist[i].Key];
newList.Add(entiy);
}
//随机法则
return newList;
}
/// <summary>
/// 随机种子值
/// </summary>
/// <returns></returns>
private static int GetRandomSeed()
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
rng.GetBytes(bytes);
return BitConverter.ToInt32(bytes, 0);
}
使用例子:
/// <summary>
/// 权重对象
/// </summary>
public class RandomObject
{
/// <summary>
/// 权重
/// </summary>
public int Weight { set; get; }
}
public class GameItemRandomObject : RandomObject
{
public int item { get; set; }
}
List<GameItemRandomObject> shuidiRanObj = new List<GameItemRandomObject>();
shuidiRanObj.Add(new GameItemRandomObject() { item = 0, Weight = 15 });
shuidiRanObj.Add(new GameItemRandomObject() { item = 1, Weight = 10 });
CurItem = MyExtansion.GetRandomList<GameItemRandomObject>(shuidiRanObj, 1)[0].item;
不带权重的随机:
/// <summary>
/// 产生从0开始的随机数
/// </summary>
/// <param name="sum">需要的随机数的个数</param>
/// <param name="max">随机的最大值,不会等于最大值</param>
/// <returns></returns>
public static int[] GetRandoms(int sum, int max)
{
max++;
if (max < 1)
{
LogTool.LogError("GetRandoms Error: max <= 1");
return null;
}
int[] arr = new int[sum];
int j = 0;
//表示键和值对的集合。
Hashtable hashtable = new Hashtable();
System.Random rm = new System.Random();
for (int i = 0; hashtable.Count < sum; i++)
{
//返回一个小于所指定最大值的非负随机数
int nValue = rm.Next(max);
//containsValue(object value) 是否包含特定值
if (!hashtable.ContainsValue(nValue) && nValue != 0)
{
//把键和值添加到hashtable
hashtable.Add(nValue, nValue);
//Debug.Log(i);
arr[j] = nValue;
j++;
}
}
int temp;
//最多做n-1趟排序
for (int i = 0; i < arr.Length - 1; i++)
{
//对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
for (j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for(int i =0;i< arr.Length; i++)
{
arr[i]--;
}
return arr;
}