带权重的随机算法及实现-创新互联

 在游戏开发过程中,经常会遇到生成一波带权重的随机怪物或是掉落List中物品带权重的情况,总结下我的算法以及实现方法。

创新互联专注于网站建设,为客户提供成都网站设计、成都网站制作、网页设计开发服务,多年建网站服务经验,各类网站都可以开发,成都品牌网站建设,公司官网,公司展示网站,网站设计,建网站费用,建网站多少钱,价格优惠,收费合理。

直接上代码

using System.Collections.Generic;

using System;

public class RandomHelper

  {

      ///

      /// 算法:

      /// 1.每个元素权重+1命名为w,防止为0情况。

      /// 2.计算出总权重n。

      /// 3.每个元素权重w加上从0到(n-1)的一个随机数(即总权重以内的随机数),得到新的权重排序值s。

      /// 4.根据得到新的权重排序值s进行排序,取前面s大几个。

      ///

      /// 原始列表

      /// 随机抽取条数

      ///

  public static List GetRandomList(List list, int count) where T : NormalStageConfig.NormalStageObject.SpawnInitialItem

      {

          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> wlist = new List>();    //第一个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(i, w));

          }

          //排序

          wlist.Sort(

            delegate(KeyValuePair kvp1, KeyValuePair kvp2)

            {

                return kvp2.Value - kvp1.Value;

            });

          //根据实际情况取排在最前面的几个

          List newList = new List();

          for (int i = 0; i < count; i++)

          {

              T entiy = list[wlist[i].Key];

              newList.Add(entiy);

          }

          //随机法则

          return newList;

      }

      ///

      /// 随机种子值

      ///

      ///

      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);

      }

  }

  ///

  /// 权重对象

  ///

  public class RandomObject

  {

      ///

      /// 权重

      ///

      public int Weight { set; get; }

  }

用法思路:写一个中转的类继承自原类,将原类中的N条数据随机取出加到新类型的list中即可


创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


网页名称:带权重的随机算法及实现-创新互联
分享链接:http://scyanting.com/article/djojis.html