Created
December 3, 2021 21:01
-
-
Save sagittaracc/8502ee9867d569392270e8d74fd090bc to your computer and use it in GitHub Desktop.
Генерация массива случайных чисел так чтобы их сумма была определенным числом
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function frand($min, $max, $decimals = 5) { | |
$scale = pow(10, $decimals); | |
return mt_rand($min * $scale, $max * $scale) / $scale; | |
} | |
function frand_by_sum($sum, $length = 2) { | |
$numbers = []; | |
for ($i = 1; $i <= $length - 1; $i++) { | |
$numbers[$i] = $sum / frand(1, 10); | |
$sum -= $numbers[$i]; | |
} | |
$numbers[] = $sum; | |
return $numbers; | |
} | |
$averageConsumption = 100; | |
$daysInMonth = 30; | |
$averageConsumptionInDay = $averageConsumption / $daysInMonth; | |
$s = 0; | |
for ($i = 1; $i <= $daysInMonth; $i++) { | |
$a = frand_by_sum($averageConsumptionInDay, 4); | |
sort($a); | |
var_dump($a); | |
$s += array_sum($a); | |
} | |
echo $s . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment