你知道一种将整数分成 5 组的方法吗?
每组总数必须是随机的,但总数必须等于固定数字。
例如我有“100”我想把这个数字分成
1- 20
2- 3
3- 34
4- 15
5- 18
编辑:我忘了说,是的,平衡是一件好事。我想这可以通过创建一个 if 语句来阻止任何超过 30 个实例的数字来完成。
我对这里的一些答案有稍微不同的方法。我根据您想要求和的项目数量创建一个宽松的百分比,然后随机加减 10%。
然后我执行 n-1 次(n 是迭代总数),这样就得到了余数。余数就是最后一个数字,它本身并不是真正的随机数,但它基于其他随机数。
效果很好。
/**
* Calculate n random numbers that sum y.
* Function calculates a percentage based on the number
* required, gives a random number around that number, then
* deducts the rest from the total for the final number.
* Final number cannot be truely random, as it's a fixed total,
* but it will appear random, as it's based on other random
* values.
*
* @author Mike Griffiths
* @return Array
*/
private function _random_numbers_sum($num_numbers=3, $total=500)
{
$numbers = [];
$loose_pcc = $total / $num_numbers;
for($i = 1; $i < $num_numbers; $i++) {
// Random number +/- 10%
$ten_pcc = $loose_pcc * 0.1;
$rand_num = mt_rand( ($loose_pcc - $ten_pcc), ($loose_pcc + $ten_pcc) );
$numbers[] = $rand_num;
}
// $numbers now contains 1 less number than it should do, sum
// all the numbers and use the difference as final number.
$numbers_total = array_sum($numbers);
$numbers[] = $total - $numbers_total;
return $numbers;
}
This:
$random = $this->_random_numbers_sum();
echo 'Total: '. array_sum($random) ."\n";
print_r($random);
Outputs:
Total: 500
Array
(
[0] => 167
[1] => 164
[2] => 169
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)