mercredi 30 septembre 2020

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

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;
    }
}



Aucun commentaire:

Enregistrer un commentaire