Skip to content
Advertisement

How to insert random values in an array with max lenght and max array sum [closed]

So, i need to make an array with lets say $n = 100 (max array length) and $target = 50 (max array values sum) with random numbers between 0-20.

I’ve tried with the below code but it gets – values when y<x.

$target = 50;
$n = 100;
while ($n) {
    if (0 < $n--) {
        $addend = rand(0, $target - ($n - 1));
        $target -= $addend;
        $addends[] = $addend;
    } else {
        $addends[] = $target;
    }
}

Advertisement

Answer

You can try next code as approach:

<?php
$addends = [];
$max_count = 100;
$max_sum = 50;
$max_value = 20;

for($i=0; $i<$max_count; $i++) {
    // generate random value between 0 and $max_sum, but not grate when $max_value
    $value = rand(0, min($max_value, $max_sum));
    // echo "rand(0, min($max_value, $max_sum)) = $value n";
    
    // decrease $max_sum to $value
    $max_sum -= $value; 
    
    // store value into array
    $addends[] = $value;
}

print_r($addends);
print_r(array_sum($addends));

Here you can try it: PHPize.online

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement