稍微有点问题
小数时,并不准确,但是整数时,经过大量测试是准确的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| class BuildPocket {
public static function build($bonus_total, $bonus_count = 2000, $bonus_max = 500, $bonus_min = 100) { if ($bonus_total / $bonus_count < $bonus_min) { throw new \Exception('红包平均值小于最小值'); } if ($bonus_total / $bonus_count > $bonus_max) { throw new \Exception('红包平均值大于最大值'); }
$result_bonus = self::getBonus($bonus_total, $bonus_count, $bonus_max, $bonus_min); return $result_bonus; }
private static function sqr($n) { return $n * $n; }
private static function xRandom($bonus_min, $bonus_max) { $sqr = intval(self::sqr($bonus_max - $bonus_min)); $rand_num = rand(0, ($sqr - 1)); return intval(sqrt($rand_num)); }
private static function getBonus($bonus_total, $bonus_count, $bonus_max, $bonus_min) { $result = array();
$average = $bonus_total / $bonus_count;
$a = $average - $bonus_min; $b = $bonus_max - $bonus_min;
$range1 = self::sqr($average - $bonus_min); $range2 = self::sqr($bonus_max - $average);
for ($i = 0; $i < $bonus_count; $i++) { if (rand($bonus_min, $bonus_max) > $average) { $temp = $bonus_min + self::xRandom($bonus_min, $average); $result[$i] = $temp; $bonus_total -= $temp; } else { $temp = $bonus_max - self::xRandom($average, $bonus_max); $result[$i] = $temp; $bonus_total -= $temp; } } while ($bonus_total > 0) { for ($i = 0; $i < $bonus_count; $i++) { if ($bonus_total > 0 && $result[$i] < $bonus_max) { $result[$i]++; $bonus_total--; } } } while ($bonus_total < 0) { for ($i = 0; $i < $bonus_count; $i++) { if ($bonus_total < 0 && $result[$i] > $bonus_min) { $result[$i]--; $bonus_total++; } } } return $result; } }
|