【发布时间】:2021-07-06 15:39:02
【问题描述】:
有一个百分比列表。数字之和为 100。
$percent = [20.88, 14.93, 14.14, 13.29, 5.06, 4.43, 4.24, 4.22, 2.57, 2.51, 2.38, 2.18, 1.94, 1.80, 1.34, 1.21, 0.81, 0.63, 0.50, 0.48, 0.30, 0.16];
我需要将最大数量限制为特定值,并将余数分配给其余数字。如果可能,保留剩余百分比的比例。
尝试了以下解决方案:
$limit = 8;
// Calculating the remainder of numbers exceeding $limit.
$rest = array_reduce($percent, function ($a, $b) use ($limit) {
return $limit < $b ? $a += ($b - $limit) : $a;
});
// Number of numbers not exceeding $limit.
$small = array_reduce($percent, function ($a, $b) use ($limit) {
return $limit > $b ? ++$a : $a;
});
// Percent calc with limit up to $limit and addition of the remainder ($rest / $small).
array_walk($percent, function(&$value) use ($limit, $rest, $small) {
$value = $limit < $value ? min($value, $limit) : $value + ($rest / $small);
});
print_r($percent);
print(array_sum($percent)) . "\n";
这段代码可以正常工作:
Array
(
[0] => 8
[1] => 8
[2] => 8
[3] => 8
[4] => 6.7955555555556
[5] => 6.1655555555556
[6] => 5.9755555555556
[7] => 5.9555555555556
[8] => 4.3055555555556
[9] => 4.2455555555556
[10] => 4.1155555555556
[11] => 3.9155555555556
[12] => 3.6755555555556
[13] => 3.5355555555556
[14] => 3.0755555555556
[15] => 2.9455555555556
[16] => 2.5455555555556
[17] => 2.3655555555556
[18] => 2.2355555555556
[19] => 2.2155555555556
[20] => 2.0355555555556
[21] => 1.8955555555556
)
100
但是如果我将变量$limit更改为值6,由于余数相加而超出限制:
Array
(
[0] => 6
[1] => 6
[2] => 6
[3] => 6
[4] => 7.24
[5] => 6.61
[6] => 6.42
[7] => 6.4
[8] => 4.75
[9] => 4.69
[10] => 4.56
[11] => 4.36
[12] => 4.12
[13] => 3.98
[14] => 3.52
[15] => 3.39
[16] => 2.99
[17] => 2.81
[18] => 2.68
[19] => 2.66
[20] => 2.48
[21] => 2.34
)
100
我找不到算法。
【问题讨论】:
-
问题在于你的定义;您必须考虑 “均匀分配剩余部分” 可能是不可能的(正如您的示例所证明的那样,限制为 6)。当无法进行这样的分发时,您必须决定到底要做什么。
-
确实,均匀分布是个坏主意。我会更正帖子,感谢您的评论。
标签: php arrays limit distribution percentage