简体   繁体   English

将数字按降序随机分配到多个点

[英]Randomize a Number over multiple points in descending order

I need to distribute a number for multiple points in degraded order. 我需要按降序分配多个点的数量。

For example, 例如,

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

Need to break 100 into 10 points in descending order RANDOMLY . 需要以降序随机将100分为10点。

eg: 例如:

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

Here, 这里,

  1. degradation will be faster towards end 退化将更快结束
  2. Must contain a zero to end 必须以零结尾

I'm trying to do something like: 我正在尝试做类似的事情:

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);
}

But nothing working. 但是没有任何作用。 Please help me. 请帮我。

Can be done with php standard functions: 可以使用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 = create array with values 1...n 范围=创建值为1 ... n的数组

shuffle = shuffle array 洗牌=洗牌数组

array_slice = return part of an array array_slice =返回数组的一部分

rsort = sort array values hight to low values rsort =将数组值从高到低排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM