php 随机几率,php实现根据概率配置随机抽奖

这是我写的一个比较简单的抽奖算法,并没有很严谨,用于我自己写的wap文字游戏(美味小镇)上的随机食材,可以设定概率值

/**

* Created by PhpStorm.

* User: tioncico

* Date: 2017/12/9 0009

* Time: 14:50

*/

class Rand

{

public $arr,$not_id,$if_repeat,$odds;

public function __construct($arr,$if_repeat=1)

{

$this->arr=$arr;

$this->if_repeat=$if_repeat;

$this->get_odds_array();

}

function action($num=1)

{

if(!$this->arr||!$this->odds){

return false;

}

$ids = array();

for ($i = 0; $i 

$res = $this->get_rand($this->arr, $this->odds);

if ($this->if_repeat == 0) {

if(count($this->arr)<=count($ids)){

return $ids;

}

if (in_array($res, $ids)) {

$i--;

} else {

$ids[] = $res;

}

} else {

$ids[] = $res;

}

}

return $ids;

}

public function get_odds_array($arr=array())

{

$arr||$arr = $this->arr;

foreach ($arr as $k => $va) {

if(empty($va['odds'])){

$va['odds']=100;

}

$odds[$k] = $va['odds'];

}

$this->odds = array_sum($odds);

return $this;

}

public function add_arr($arr=array()){

$this->arr = array_merge($this->arr,$arr);

return $this;

}

function remove_id($arr=array(),$not_id=array()){

$arr||$arr = $this->arr;

$not_id||$not_id = $this->not_id;

if(empty($not_id)){

$this->arr = $arr;

return $this;

}

foreach($arr as$k=> $va){

foreach($not_id as $vo){

if($k==$vo){

unset($arr[$k]);

}

}

}

$this->arr = $arr;

return $this;

}

//返回概率

function get_rand($arr=array(), $odds=0)

{

$arr||$arr = $this->arr;

$odds||$odds = $this->odds;

//概率数组循环

$randNum = mt_rand(1, $odds);

$odd_num = 0;

foreach ($arr as $key => $va) {

if ($randNum > $odd_num && $randNum <= $va['odds'] + $odd_num) {

return $arr[$key];

break;

} else {

$odd_num += $va['odds'];

}

}

unset ($proArr);

}

}

$arr=array(

array(

'id'=>1,

'odds'=>100//相对概率值

),

array(

'id'=>2,

'odds'=>10//相对概率值

),

array(

'id'=>3,

'odds'=>200//相对概率值

),

)

调用方法

$a = new Rand($arr);

$a->action(1);

本文为仙士可原创文章,转载无需和我联系,但请注明来自仙士可博客www.php20.cn

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值