Random Red envelope algorithm

Source: Internet
Author: User
Tags numeric value

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.