我需要随机算法与.NET权衡选项 [英] I need random algorithm with weighing options in .net

查看:110
本文介绍了我需要随机算法与.NET权衡选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET项目的要求,我需要从集合中选择一个项目,每一个项目都有一个重量(整数1到10)分配给它。我需要一个随机发生器,将借此重量考虑即重量越高,更多的机会的对象将被选中。在.net中的任何code样品AP preciated,虽然算法描述很不错了。 谢谢

编辑:快速复制/粘贴C#code,以防有人绊倒在此

 类RandomWeightedSelector< T>
    {
        私人列表< T>项目=新的名单,其中,T>();

        公共无效添加(T项目,UINT重量= 1)
        {
            的for(int i = 0; I<重;我++)
                items.Add(项目);
        }

        公共牛逼GetRandom()
        {
            退换货品[新的随机()下(0,items.Count)];
        }
    }
 

解决方案

下面是一个算法,它不需要添加项目多次到列表。它也可以用非整数权重的工作,但如果你使用的是NextDouble从System.Random,你必须缩放所有的权重加起来为1,或乘值从NextDouble带S得到它在在所需的范围。

鉴于产品(I,W),其中I是该项目,W是重量的列表L

  1. 添加所有的权重一起。调用该合计值S。
  2. 生成介于0和S的一个随机数(不含S,但包括0)。调用这个R值。
  3. 初始化变量为0,以跟踪运行总数。我们会打电话给这件T。
  4. 对于L中的每个项目(I,W):
    1. T = T + W
    2. 如果T> R,返回我。

I have a requirement in my .net project where I need to select an item from a collection, each item has a Weight (integer from 1 to 10) assigned to it. I need a random generator that would take this weight into consideration i.e. the higher the weight, the more chances the object would be selected. Any code samples in .net are appreciated, although algorithm description is nice, too. Thanks

Edit: Quick copy/paste C# code in case someone stumbles upon this.

    class RandomWeightedSelector<T>
    {
        private List<T> items = new List<T>();

        public void Add(T item, uint weight = 1)
        {
            for (int i = 0; i < weight; i++)
                items.Add(item);
        }

        public T GetRandom()
        {
            return items[new Random().Next(0, items.Count)];
        }
    }

解决方案

Here's an algorithm which doesn't require adding the items multiple times to a list. It can also work with non-integer weights, although if you're using NextDouble from System.Random, you'll have to scale all of the weights to add up to 1, or multiply the value from NextDouble with S to get it in the desired range.

Given a list L of items (I,W), where I is the item and W is the weight:

  1. Add all of the weights together. Call this sum S.
  2. Generate a random number between 0 and S (excluding S, but including 0). Call this value R.
  3. Initialize a variable to 0 to keep track of the running total. We'll call this T.
  4. For each item (I,W) in L:

    1. T=T+W
    2. If T > R, return I.

这篇关于我需要随机算法与.NET权衡选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆