Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate an array of random integers that averages (or closes) to a given float or integer
<?php
function getRandomintegersFloatAvg($target, $count, $min = 1, $max = 5, $precision = 2) {
if ($target > $max) return FALSE;
if ($target < $min) return FALSE;
if ($count < 1) return FALSE;
if ($count === 1) return array(round($target));
$values = array();
for ($i = 0; $i < $count; $i++) {
$values[] = mt_rand($min, $max);
}
$distance = round($target - (array_sum($values) / $count));
$target = round($target, $precision);
$avg = round(array_sum($values) / $count, $precision);
if ($distance !== 0) {
$adjuster = $distance > 0 ? 1 : -1;
$i = 0;
while ($i != $distance) {
$random_key = array_rand($values);
$values[$random_key] += $adjuster;
$i += $adjuster;
}
}
return $values;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.