例如我有这样的元素和数组:
0 21 29 0 0 50
让我们“扁平化”这个数字:
假设我的随机数是 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/