PHP divides a number into random values, the sum is the same as the number today there is a task, very strange, need to divide a numeric value into the number of x, the value of each number is random, but the random number of the sum must = total. For example, there is a number is 100, I would like to divide him into 5 (or n), each share of the number is not the same, but add up if 100, and each part can not be too big, this use PHP how to achieve? So we need the following PHP to divide a number into random values, the sum of the same function as the number of the general idea 1) the average of the number of copies 2) according to the maximum difference between the allowable number of parts, the dynamic adjustment of the range of random numbers to form the number of Parts 3) The last part of the number of the previous decision, To guarantee the sum of the parts for the specified value Cenxi Web site development provides functions: http://www.12345t.com/0) {$max = 0; $min = 0-round ($area/2); }elseif ($sum [1] = [2] = [3] = 2 [4] + 34) The result shows that the size of the returned array is basically the same, the sum of each number equals the total, and the task is completed!
<?PHPHeader("Content-type:text/html;charset=utf-8");$total= 20;//Total Red Envelopes$num= 10;//divided into 10 red envelopes, support 10 people randomly pick up$min= 0.01;//everyone receives at least 0.01 yuan for($i= 1;$i<$num;$i++) { $safe _total=($total-($num-$i)*$min)/($num-$i);//Random Security Cap $money=Mt_rand($min*100,$safe _total*100)/100; $total=$total-$money; $arr[' Res '] [$i] =Array( ' I ' + =$i, ' money ' =$money, ' total ' =$total );} $arr[' Res '] [$num] =Array(' I ' =$num, ' money ' =$total, ' Total ' =>0);$arr[' msg '] = 1;EchoJson_encode ($arr);?>
Random Red envelope algorithm