php - 在数组中创建总计为设定数量的数字

标签 php arrays

我是 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

此外,不允许重复,所有数字都必须是正整数。

我需要数组中的值。我一直在搞乱它,但是,我的知识相当有限。任何帮助将不胜感激。

最佳答案

首先,这是一个非常酷的问题。我几乎可以肯定我的方法甚至不能完美地分配数字,但它应该比这里的其他一些方法更好。

我决定从最小的数字开始构建数组(并在最后打乱它们)。这使我始终可以选择一个随机范围,以产生有效结果。由于数字必须始终增加,我解决了确保有效解决方案仍然存在的最大可能数字(即,如果 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 );

编辑:对于较大的 $n 值,您最终会在数组末尾得到很多分组值,因为您很有可能会在接近最大值迫使其余的非常接近。一个可能的解决办法是使用加权兰特,但这超出了我的范围。

关于php - 在数组中创建总计为设定数量的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2793797/

相关文章:

javascript - 为什么我们需要 json 或 php 的序列化方法来在 JS 中访问 php 数组,如果没有它们也能实现同样的效果?

php - 策划新闻订购系统

php - Cron 在 ubuntu (digitalocean) 中不起作用

返回星期几 x 天数后的 javascript 函数

java - 如何将 ExpandableListView 的选定项目存储在 ArrayList 中

php - 在可调用的set_error_handler中获取产生错误的函数名称

php - 第一次需要建立一个全面的电子商务页面--Magento?

java - Java从数组中删除项目

php - 查找数组中的所有差异

c# - C# OOP 说明