zoukankan      html  css  js  c++  java
  • 抽奖概率控制 (简便)

     /**
         * 根据给定概率随机选择一项
         * @param $itemArray array("奖项1","奖项2"....);
         * @param $chanceArray  array("10","50","40","70")  数组的一个参数/所有参数加起来 == 这项奖项的概率
         * @return int|null     返回$itemArray中被选中的索引,逻辑有错误时返回NULL
         */
        public static function pickOne($itemArray, $chanceArray = NULL){
           $index = NULL;
            if($itemArray){
                if(sizeof($itemArray) <= 0){
                    return NULL;
                }
            }
    
            if($chanceArray){
    
                if(sizeof($chanceArray) <= 0 || sizeof($chanceArray) != sizeof($itemArray)){
                    return NULL;
                }
    
                if(sizeof($chanceArray) == 1){
                    return 0;
                }
    
                $fullChance = 0;
                foreach($chanceArray as $value){
                    $fullChance += $value;
                }
                if($fullChance <= 0){
                    return NULL;
                }
    
                //参数正常,给予默认的第一项
                $index = 0;
    
                $baseChance = 0;
                $ranum = rand(0, $fullChance - 1);
                for($i = 1 ; $i < sizeof($itemArray) ; $i++){
                    if($ranum >= $baseChance && $ranum < ($baseChance + $chanceArray[$i])){
                        $index = $i;
                        break;
                    }
                    $baseChance += $chanceArray[$i];
                }
            }else{
                //参数正常,给予默认的第一项
                $index = 0;
                $index = rand(0, sizeof($itemArray) - 1);
            }
    
            return $index;
        }
  • 相关阅读:
    Flutter 导航栏上添加搜索按钮
    tabController保活
    nav 选项卡
    flutter 毛玻璃
    [题解]CodeForces878 D
    [题解]CodeForces878C Tournament
    [题解]NOIP2012
    bzoj1070题解
    bzoj1061题解
    bzoj1059题解
  • 原文地址:https://www.cnblogs.com/renshi/p/4334352.html
Copyright © 2011-2022 走看看