如何将大的正整数 n 分成 m > EM>。 后置条件:添加所有 m 部分应该给出 n 。
下面是我的尝试(在java中像伪代码),但我不认为它会给我统一的随机分布。 我首先通过除以n / m来找到平均部分 avg 。然后我生成 m-1 随机数,其大小约为平均值(通过交替生成 0& avg 之间的随机数,以及* avg& 2 * avg *然后我从原始数字 n 中减去这些 m-1 数字的总和,并将其设置为 m '部分。
假设函数 rand(x,y)在x和y之间均匀地返回一个随机数。
int[] divideUniformlyRandomly(int n, int m)
{
int[] res = new int[m];
int avg = n / m;
int sum = 0;
bool alternator = false;
for(int i = 0; i < m - 1; i++)
{
if(alternator == false)
{
res[i] = rand(0, avg);
alternator = true;
}
else
{
res[i] = rand(avg, 2*avg);
alternator = false;
}
sum += res[i];
}
res[m-1] = n - sum;
return res;
}
答案 0 :(得分:4)
public double[] divideUniformlyRandomly(double number, int part) {
double uniformRandoms[] = new double[part];
Random random = new Random();
double mean = number / part;
double sum = 0.0;
for (int i=0; i<part / 2; i++) {
uniformRandoms[i] = random.nextDouble() * mean;
uniformRandoms[part - i - 1] = mean + random.nextDouble() * mean;
sum += uniformRandoms[i] + uniformRandoms[part - i -1];
}
uniformRandoms[(int)Math.ceil(part/2)] = uniformRandoms[(int)Math.ceil(part/2)] + number - sum;
return uniformRandoms;
}
public double[] divideUniformlyRandomly(double number, int part) {
double uniformRandoms[] = new double[part];
Random random = new Random();
double mean = number / part;
double sum = 0.0;
for (int i=0; i<part / 2; i++) {
uniformRandoms[i] = random.nextDouble() * mean;
uniformRandoms[part - i - 1] = mean + random.nextDouble() * mean;
sum += uniformRandoms[i] + uniformRandoms[part - i -1];
}
uniformRandoms[(int)Math.ceil(part/2)] = uniformRandoms[(int)Math.ceil(part/2)] + number - sum;
return uniformRandoms;
}
答案 1 :(得分:0)
你应该使用m - 1个均匀分布的围栏来划分m个m部分。您的代码可能是:
int[] divideUniformlyRandomly(int n, int m)
{
int[] fences = new int[m-1];
for(int i = 0; i < m - 2; i++)
{
fences[i] = rand(0, n-1);
}
Arrays.sort(fences);
int[] result = new int[m];
result[0] = fences[0];
for(int i = 1; i < m - 2; i++)
{
result[i] = fences[i+1] - fences[i];
}
result[m-1] = n - 1 - fences[m-2];
return result;
}
为了说明这一点: