Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Created December 3, 2021 21:01
Show Gist options
  • Save sagittaracc/8502ee9867d569392270e8d74fd090bc to your computer and use it in GitHub Desktop.
Save sagittaracc/8502ee9867d569392270e8d74fd090bc to your computer and use it in GitHub Desktop.
Генерация массива случайных чисел так чтобы их сумма была определенным числом
<?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