Skip to content

Instantly share code, notes, and snippets.

@Ayesh
Created March 14, 2015 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ayesh/e949642860a01c350b29 to your computer and use it in GitHub Desktop.
Save Ayesh/e949642860a01c350b29 to your computer and use it in GitHub Desktop.
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