c# - 带有随机数 : get interval where random belongs to 的平面轮盘赌

标签 c# algorithm roulette-wheel-selection

例如我有这样的元素和数组:

0 21 29 0 0 50

让我们“扁平化”这个数字:

enter image description here

假设我的随机数是 54,所以我的数字属于数组中索引为 6 的最后一个元素(它是 50)

我不明白,如何用 C# 算法化...

我尝试:

  Random random = new Random();
            int randomNumber = random.Next(1, 100);
            int temp, temp_ind;
            float a_, b_;
            for (j = 0; j < n-1; j++)
            {
                if (roulette[j] != 0)
                {
                    temp_ind = j+1;
                    a_ = roulette[j];
                    while ((roulette[temp_ind] == 0.0) && (temp_ind < n-1))
                    {
                        temp_ind++;
                    }
                    b_ = roulette[temp_ind];
                    if ((a_ <= randomNumber) && (b_ >= randomNumber))
                    {
                        start = j;
                        break;
                    }
                }
            }

但这行不通,也许有什么可以帮助我?

最佳答案

这是一个将数组转换为累积数组的解决方案(使用来自 Eric Lippert 的 this 回答的扩展方法),然后找到该数组中高于随机数的第一个匹配项的索引。

class Program
{
    static void Main(string[] args)
    {
        var random = new Random();
        int[] roulette = { 0, 21, 29, 0, 50 };

        var cumulated = roulette.CumulativeSum().Select((i, index) => new { i, index });
        var randomNumber = random.Next(0, 100);
        var matchIndex = cumulated.First(j => j.i > randomNumber).index;

        Console.WriteLine(roulette[matchIndex]);
    }
}

public static class SumExtensions
{
    public static IEnumerable<int> CumulativeSum(this IEnumerable<int> sequence)
    {
        int sum = 0;
        foreach (var item in sequence)
        {
            sum += item;
            yield return sum;
        }
    }
}

关于c# - 带有随机数 : get interval where random belongs to 的平面轮盘赌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20939170/

相关文章:

c# - 使用DirectSound进行音高转换

algorithm - 播放或访问时蒙特卡洛树搜索中的置信上限为 0

flash - 聊天轮盘的架构

genetic-algorithm - 遗传算法中的轮盘选择

c# - 从部分模拟对象返回模拟对象不起作用

c# - 尽管更改分辨率,视频捕获输出始终为 320x240

java - 插入排序的问题

python-3.x - 如何根据该模型上的权重字段快速获取 Django 模型实例的加权随机实例?

algorithm - 遗传算法: Roulette wheel selection

c# - 在 C# 中,如果 2 个进程正在读取和写入同一个文件,避免进程锁定异常的最佳方法是什么?