按降序在多个点上随机化一个数字


Randomize a Number over multiple points in descending order

我需要按降级顺序为多个点分配一个数字。

例如,

N = 100 // this 100 is fixed
no_of_points = 10 // no of points will vary 

需要按降序将100分解为10个点随机

例如:

80, 55, 32, 18, 10, 10, 10, 8, 2, 0

这里,

  1. 退化将在接近尾声时更快
  2. 结尾必须包含零

我正在尝试做一些类似的事情:

private static function generateRandomPercentage($no_of_points)
{
    $distributions = [];
    // need to start from 80
    // but it may vary also
    $max = mt_rand(80, 81);
    $ratio = $max / $no_of_points;
    for( $i = 1; $i <= $no_of_points; $i++ ) {
        $delta = ($ratio * $i);
        $distributions[] = round(($max - $delta) / 100, 2);
    }
    print_r($distributions);
}

但什么都不管用。请帮帮我。

可以用php标准函数完成:

$N = 100 // this 100 is fixed
$no_of_points = 10 // no of points will vary
$distributions= rsort(array_slice(shuffle(range(1,$N)), 0, $no_of_points);
print_r($distributions));

range=创建值为1…n的数组

shuffle=shuffle阵列

array_slice=返回数组的一部分

rsort=从高到低对数组值进行排序