Home > Backend Development > PHP Tutorial > PHP lottery probability algorithm implementation code

PHP lottery probability algorithm implementation code

高洛峰
Release: 2023-03-05 11:18:01
Original
1641 people have browsed it

Implementation code:

<?php
/**
 *php 中奖概率算法
 *
 */
function get_zj( $jp ,$glname = &#39;gl&#39;){
    $sum = 0;
    foreach($jp as $k =>$v ){
        $sum += $v[$glname];
    }
  
    $R = rand(1,$sum);//获取随机数
  
    foreach( $jp as $k => $v){
        if( $R <= $v[$glname] ){
            return $v;
        }
        $R = $R - $v[$glname] ;
    }
  
}
  
  
//使用方法
//模拟一个从数据库中读取的 中奖配置  gl 为 中奖的概率 
//例如array( &#39;gl&#39; => 10 , &#39;title&#39; => &#39;一等奖&#39;);的中奖概率 = 10 / (10+20+30+40)
$jp = array();
$jp[] = array( &#39;gl&#39; => 10 , &#39;title&#39; => &#39;一等奖&#39;);
$jp[] = array( &#39;gl&#39; => 20 , &#39;title&#39; => &#39;二等奖&#39;);
$jp[] = array( &#39;gl&#39; => 30 , &#39;title&#39; => &#39;三等奖&#39;);
$jp[] = array( &#39;gl&#39; => 40 , &#39;title&#39; => &#39;未中奖&#39;);
  
  
//调用 中奖概率函数 
//返回中奖 信息数组 例如:array( &#39;gl&#39; => 10 , &#39;title&#39; => &#39;一等奖&#39;);
$zj = get_zj( $jp );
  
//输出数组
var_dump($zj);
Copy after login

Usage method
Simulate a winning configuration gl read from the database as the probability of winning
For example array('gl' => 10, 'title' => 'First Prize'); probability of winning = 10 / (10+20+30+40)
$jp = array();
$jp[] = array( 'gl' => ; 10 , 'title' => 'First Prize');
$jp[] = array( 'gl' => 20 , 'title' => 'Second Prize');
$jp[] = array( 'gl' => 30 , 'title' => 'Third Prize');
$jp[] = array( 'gl' => 40 , 'title' = > 'Not winning');

Call the winning probability function
Return the winning information array. For example: array('gl' => 10, 'title' => 'First prize');

For more articles related to PHP winning probability algorithm implementation code, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template