我对PHP很新 - 一般编程.基本上我需要完成的是,创建一个x数量的数组(随机创建),其值加起来为n:
让我们说,我必须创建4个加起来为30的数字.我只需要第一个随机数据集.这里的4和30是将由用户设置的变量.
基本上是这样的
x = amount of numbers;
n = sum of all x's combined;
// create x random numbers which all add up to n;
$row = array(5, 7, 10, 8) // these add up to 30
Run Code Online (Sandbox Code Playgroud)
此外,不允许重复,并且所有数字必须是正整数.
我需要数组中的值.我有时候一直在乱搞它,但是,我的知识相当有限.任何帮助将不胜感激.
首先,这是一个非常酷的问题.我几乎可以肯定我的方法甚至不能完美地分配数字,但它应该比其他一些方法更好.
我决定从最低的数字开始构建数组(并在最后将它们洗牌).这允许我总是选择一个允许产生有效结果的随机范围.由于数字必须一直在增加,我解决了确保有效解决方案仍然存在的最高可能数量(即,如果n = 4且max = 31,如果第一个数字被选为7,则不会可以选择大于7的数字,使得4个数字的总和等于31).
$n = 4;
$max = 31;
$array = array();
$current_min = 1;
while( $n > 1 ) {
//solve for the highest possible number that would allow for $n many random numbers
$current_max = floor( ($max/$n) - (($n-1)/2) );
if( $current_max < $current_min ) throw new Exception( "Can't use combination" );
$new_rand = rand( $current_min, $current_max ); //get a new rand
$max -= $new_rand; //drop the max
$current_min = $new_rand + 1; //bump up the new min
$n--; //drop the n
$array[] = $new_rand; //add rand to array
}
$array[] = $max; //we know what the last element must be
shuffle( $array );
Run Code Online (Sandbox Code Playgroud)
编辑:对于较大的值,$n
你最终会在阵列末尾有很多分组值,因为很有可能你会得到一个接近最大值的随机值,迫使其余值非常接近.一个可能的解决方案是加权兰特,但这超出了我的范围.