C# 带权重的随机 与 不带权重的随机

本文介绍了一种带权重的随机选择算法实现,适用于游戏开发及各类需要按概率选取元素的应用场景。该算法通过计算每个对象的权重来决定其被选中的概率,并通过随机种子确保每次调用的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

带权重的随机:

 /// <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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

耳朵里有只风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值