• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

根据人数随机分配百分比的问题

php 搞代码 3年前 (2022-01-23) 55次浏览 已收录 0个评论
文章目录[隐藏]

需求是这样的,根据可变参数 $people 来给每个人随机分配百分比,条件是人数一定会控制在 3 < N < 100,弱条件是尽量保证每个人分配到的比例在 30% 一下,不会出现极值。

写了个简单的分配,但会出现最后一个人会得到很多的情况,并且由于分配区间实际上是 1 – 平均数 之间的百分比,不是严格意义上的 “随机平均分配”,求各位大大给个思路,抛砖引玉,不甚感谢。

$people = 3;     //人数        $percent = 100;   //百分比        $average = floor($percent/$people);        $rand_array = array();        $count = 0;        for ($i=0; $i < $n; $i++) {            if($i == ($n - 1)){                $rand_array[$i] = 100 - $count;            }else{                $rand_array[$i] = rand(1,$average);                $count = $count + $rand_array[$i];             }        }        return $rand_array;

回复讨论(解决方案)

这样可能好点

$people = 3;    //人数$percent = 100; //百分比$res = array_fill(0, 3, floor($percent/$people)); //平均分配$d = 5; //容差foreach($res as &$v) $v += rand(-$d, $d);$res[rand(0, $people-1)] += $percent - array_sum($res); //随机将残差补入print_r($res);

忘记上来结贴了,感谢版主大大的回复,问题已经解决了,贴出来与大家分享:

public static function rand_bouns($person){		//百分比		$percent = 100;		$now_person = $person;		$bouns = array();		for($i=0;$i<=$person-1;$i++){			$bouns[$i] = self::get_bouns($now_person,$percent);			$percent = $percent - $bouns[$i];			$now_person = $now_person - 1;			$now_bouns += $bouns[$i];		}		return $bouns;			}public static function get_bouns($person,$percent){		if($person==1) return $percent;		$max = 30;		if($percent < $max)  $max = $percent;		$min = $percent-$max*($person-1) <= 0 ? 1 : $percent-<strong style="color:transparent">9来源gaodai#ma#com搞@代~码$网</strong>搞gaodaima代码$max*($person-1);		$max = $max-($person) <= 0 ? 1 : $max-($person);		return rand($min,$max);	}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:根据人数随机分配百分比的问题
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址