我有5个字段,我希望它们都有0到100之间的生成数字.但是,5个字段的总和应该是100.
当我想为一个字段提供一个随机数时,我会做以下事情:
Random rnd = new Random();
int x= rnd.Next(1, 10);
Run Code Online (Sandbox Code Playgroud)
但是,我应该如何为需要总和为100的多个字段执行此操作?
您可以使用以下方法:
它基本上对应于在[0,100]间隔上随机添加4个切片点,并使用5个结果间隔的长度作为随机数:
const int k = 5;
const int sum = 100;
Random rnd = new Random();
int[] x = new int[k + 1];
// the endpoints of the interval
x[0] = 0;
x[k] = sum;
// generate the k - 1 random sectioning points
for (int i = 1; i < k; i++)
{
x[i] = rnd.Next(0, sum + 1);
}
// sort the sectioning points
Array.Sort(x);
// obtain the k numbers with sum s
int[] N = new int[k];
for (int i = 0; i < k; i++) {
N[i] = x[i + 1] - x[i];
}
Run Code Online (Sandbox Code Playgroud)
为了使你的分布均匀,你可以尝试以下方法:
代码:
const int ExpectedSum = 100;
Random rnd = new Random();
int[] fields = new int[5];
// Generate 4 random values and get their sum
int sum = 0;
for (int i = 0; i < fields.Length - 1; i++)
{
fields[i] = rnd.Next(ExpectedSum);
sum += fields[i];
}
// Adjust the sum as if there were 5 random values
int actualSum = sum * fields.Length / (fields.Length - 1);
// Normalize 4 random values and get their sum
sum = 0;
for (int i = 0; i < fields.Length - 1; i++)
{
fields[i] = fields[i] * ExpectedSum / actualSum;
sum += fields[i];
}
// Set the last value
fields[fields.Length - 1] = ExpectedSum - sum;
Run Code Online (Sandbox Code Playgroud)
实例: https: //dotnetfiddle.net/5yXwOP