C# 按照比重来随机 [搬运微调]
本文章时在原文章基础上添加了一丢丢测试代码
***用途,按照比重来进行随机
测试代码:
int viewCount1 = 0; int viewCount0 = 0; for (int i = 0; i < 5000; i++) { List<GameItemRandomObject> shuidiRanObj = new List<GameItemRandomObject>(); shuidiRanObj.Add(new GameItemRandomObject() { item = 0, Weight = 15 }); shuidiRanObj.Add(new GameItemRandomObject() { item = 1, Weight = 10 }); var obj = GetRandomList<GameItemRandomObject>(shuidiRanObj, 1)[0].item; if (obj.Equals(1)) viewCount1 += 1; if (obj.Equals(0)) viewCount0 += 1; } Console.WriteLine($"五千次测试结果: 0比重15共出现{viewCount0}次,1比重10共出现{viewCount1}次");
以下是原文代码:
/// <summary> /// 权重对象 /// </summary> public class RandomObject { /// <summary> /// 权重 /// </summary> public int Weight { set; get; } } public class GameItemRandomObject : RandomObject { public int item { get; set; } }
/// <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); }
分类:
每天十篇博文系列计划
, C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库