# 按权重产生随机数

###题目

int randomByWeight(int[] weights)
{

}

###代码

using System;

public class Test
{
public static void Main()
{
int[] weights = new int[]{5, 5, 3, 1};
int number = RandomByWeight(weights);
Console.WriteLine("return prize is {0}", number);
}

public static int RandomByWeight(int[] weights)
{
for(int i = 1; i < weights.Length; i++)
{
weights[i] += weights[i-1];
Console.WriteLine("weights[{0}] = {1}", i, weights[i]);
}
int sum = weights[weights.Length-1];
int number_rand = rand(sum);
Console.WriteLine("number_rand = {0}", number_rand);

if(0 <= number_rand && number_rand < weights[0])
{Console.WriteLine("{0} <= {1} < weights[0]={2}", 0, number_rand, weights[0]);return 0;}
for(int i = 1; i < weights.Length; i++)
{
if(weights[i-1] <= number_rand && number_rand < weights[i])
{
Console.WriteLine("weights[{0}]={1} <= {2} < weights[{3}]={4}", i-1, weights[i-1], number_rand, i, weights[i]);
return i;
}
}
return -1;
}

static int rand(int n)
{
Random rd = new Random();
return rd.Next(0, n);
}
}

###输出

weights[1] = 10
weights[2] = 13
weights[3] = 14
number_rand = 12
weights[1]=10 <= 12 < weights[2]=13
return reward is 2

###补充

###改进后的代码

using System;

public class Test
{
public static void Main()
{
int[] table = new int[]{10, 20, 30, 40, 50};
Console.WriteLine("result = " + RandomByWeight(table));
}

public static int RandomByWeight(int[] weights)
{
int sum = 0;
for(int i = 0; i < weights.Length; i++)
{
sum += weights[i];
}
int number_rand = rand(sum);
Console.WriteLine("number_rand = " + number_rand);

int sum_temp = 0;

for(int i = 0; i < weights.Length; i++)
{
sum_temp += weights[i];
if(number_rand <= sum_temp){return i;}
}

return -1;
}

static int rand(int n)
{
Random rd = new Random();
return rd.Next(0, n);
}
}

###输出

number_rand = 46
result = 2
---------------------

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客