Created
March 14, 2015 01:27
-
-
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
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 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