php - 用随机数填充数组,同时遵守指定的总和、计数和数字边界

标签 php arrays random

我必须用随机数填充数组以满足一些条件:

  1. 结果数组中的元素数量必须与指定数量匹配。
  2. 结果数组中的数字之和必须等于指定的数字。
  3. 必须在指定的下限和上限之间选择随机数。

例如:

  • 数组总和:130
  • 数组元素总数:3
  • 随机整数的下限:23
  • 随机整数的上限:70

可能的结果:

array(23, 70, 37)

现在该怎么办?如何拆分/划分我的号码?

我从这个开始(伪代码):

i=0;
while(sum(number) > 0 and i < arraykeys){
    x = randomize(from, to)
    number = number - x
    myarray[i] = x
    i++
} 

最佳答案

这应该适合你:

代码说明

  1. 可加工性

    我们需要检查的第一件事是,是否可以利用范围内的数字来构建目标:

    if(checkWorkability($result, $goal, $amountOfElementsLeft, $scope))
    

    意味着它只使用可能的最高值,并查看它是否大于目标。

  2. While循环

    在 while 循环中,我们需要检查是否还有可以使用的元素:

    while($amountOfElementsLeft > 0)
    
  3. 范围调整

    每次迭代我们都需要检查是否需要调整范围,以便最终我们能够构建目标。

    这意味着如果当前数字之和+最大可能数字大于目标,我们需要减小范围的最大值。

    另一方面,当我们无法再达到目标时,我们需要增大范围的最小值。

代码

<?php


    $goal = 130;
    $amountOfElementsLeft = 3;
    $scope = [23, 70];

    $result= [];


    function adjustScope(array $result, $goal, $amountOfElementsLeft, $scope) {

        $newScope = $scope;

        if($amountOfElementsLeft == 1) {
            $leftOver = $goal - array_sum($result);
            return [$leftOver, $leftOver];
        }


        if((($goal - (array_sum($result) + $scope[1])) / ($amountOfElementsLeft - 1)) < $scope[0])
            $newScope[1] = (int) ($goal - array_sum($result)) / ($scope[0] * ($amountOfElementsLeft - 1));
        elseif(($adjustTop = $goal - array_sum($result)) < $scope[1])
            $newScope[1] = $adjustTop;

        if(($adjustBottom = $goal - (array_sum($result) + $scope[0] + (($amountOfElementsLeft - 1) * $scope[1]))) < $goal && $adjustBottom > 0)
            $newScope[0] = $scope[0] + $adjustBottom;

        return $newScope;

    }

    function checkWorkability(array $result, $goal, $amountOfElementsLeft, $scope) {
        if(array_sum($result) + $amountOfElementsLeft * $scope[1] >= $goal)
            return TRUE;
        return FALSE;
    }


    if(checkWorkability($result, $goal, $amountOfElementsLeft, $scope)) {
        while($amountOfElementsLeft > 0) {
            $scope = adjustScope($result, $goal, $amountOfElementsLeft, $scope);

            $result[] = rand($scope[0], $scope[1]);
            $amountOfElementsLeft--;

        }
    }

    print_r($result);
    echo array_sum($result);

?>

可能的输出:

Array
(
    [0] => 58
    [1] => 30
    [2] => 42
) -> 130
Array
(
    [0] => 35
    [1] => 54
    [2] => 41
) -> 130
Array
(
    [0] => 52
    [1] => 51
    [2] => 27
) -> 130

关于php - 用随机数填充数组,同时遵守指定的总和、计数和数字边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32979029/

相关文章:

php pdo只返回一个结果集

c# - 如何从文本文件中的另一行向下读取 X 行?

arrays - 在两个元素的数组中拆分大数组

ios - 如果将某种类型传递给 Swift 中的函数,如何返回 nil?

javascript - 在 ReactJS 中设置状态的条件(三元)运算符

php - Cookie 与基于 Session 的 flash 消息

php - 在heroku上编辑php.ini

php - 带有特殊字符的目标 URL

java - 将字符串从 ElementValue 转换为数组

random - 是否有一个随机数生成器可以在 O(1) 中跳过/丢弃 N 次绘制?