根據人數隨機分配百分比的問題

來源:互聯網
上載者:User
需求是這樣的,根據可變參數 $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-$max*($person-1);$max = $max-($person) <= 0 ? 1 : $max-($person);return rand($min,$max);}
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.