千分之多少) ****/
$awards=array(
1=>10, /**** 一獎個數 ****/
2=>20, /**** 二獎個數 ****/
3=>70, /**** 三獎個數 ****/
);
$awardsTot=array_sum($awards);
if($awardsTot<1)die('end');
srand($awardsTot + date('U'));
$n=rand(1,1000);
if($n<=$noaward)die('沒中');/**** 先排除沒中獎的 ****/
$m=count($awards);
/*** 讓 $n 在 1~$awardsTot 之間 ***/
$n=round(($n-$noaward)*$awardsTot/(1000-$noaward));
foreach($awards as $k => $v){
if($n<=$v){
break;
}
$n-=$v;
}
if($awards[$k]>0){
echo '中了第'.$k.'獎';
$awards[$k]-=1;/**** 各獎剩幾個應該是要存資料庫吧? ****/
}
else{
/**** 避免意外,意料外的狀況都沒沒中獎 :p ****/
echo '沒中';
}
※ 引述《s861175 (s861175)》之銘言:
: 想寫一個抽獎遊戲的網頁,使用者點擊後開始抽獎,
: "1獎"中獎機率為10%
: "2獎"中獎機率為20%
: "3獎"中獎機率為70%
: 在程式碼部分,小弟想到的是
: $arr=array("1獎","2獎","2獎","3獎","3獎","3獎","3獎","3獎","3獎","3獎");
: shuffle($arr); //將陣列元素隨機排序
: echo $arr[0];
: 是很直覺的寫法
: 但是,如果要應付1獎中獎機率只有0.1%的情況,
: 那陣列就會變成有1千個元素,感覺效能會很差,
: 請問大家會建議用什麼樣的寫法,謝謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 211.76.137.169
$noaward=0; /**** 沒中獎機率(