每个人至少6块钱,所以现每个人给6块钱,还剩40块钱,只要满足每个人不超过12块钱的条件就行了,上代码:
$cash = 40;
$user_arr = array(6,6,6,6,6,6,6,6,6,6);
while($cash > 0){
$uid = rand(0,9);
if($user_arr[$uid] < 12){
$user_arr[$uid]++;
$cash--;
}
}
$result = json_encode($user_arr);
var_dump($result);
刚开始看到这个问题有点懵,是因为一般都是要求穷举出来各种可能,而这里面是只需要举出一种随机结果就行。
结果为:
D:\Program Files (x86)\360\skylar6\php>php 3.php
string(27) "[8,11,12,9,10,11,9,11,9,10]"
D:\Program Files (x86)\360\skylar6\php>php 3.php
string(28) "[12,9,7,11,7,10,10,12,11,11]"
D:\Program Files (x86)\360\skylar6\php>php 3.php
string(25) "[12,11,9,9,9,12,12,9,9,8]"
D:\Program Files (x86)\360\skylar6\php>php 3.php
string(28) "[7,9,8,10,10,10,12,10,12,12]"
D:\Program Files (x86)\360\skylar6\php>php 3.php
string(26) "[11,8,12,11,11,8,9,9,12,9]"
D:\Program Files (x86)\360\skylar6\php>