Home > Backend Development > PHP Tutorial > Introduction to PHP random probability calculation function

Introduction to PHP random probability calculation function

不言
Release: 2023-04-03 06:24:01
Original
2460 people have browsed it

This article mainly introduces the introduction of PHP random probability calculation function. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.

In game development, you will often encounter To the scenario of calculating probability
The following code is the simplest example of calculating a random result based on a given probability

<?php
//a出现的概率是10%,b是20%,c是30%,d是40%
$pro = [
&#39;a&#39; =>10,
&#39;b&#39; =>20,
&#39;c&#39; =>30,
&#39;d&#39; =>40
];

function proRand($pro)
{
        $ret = &#39;&#39;;
        $sum = array_sum($pro);
        foreach($pro as $k=>$v)
        {   
                $r = mt_rand(1, $sum);
                //echo $r . "\t" . $v . "\n";
                if($r <= $v) 
                {   
                        $ret = $k; 
                        break;
                }else{
                        $sum = max(0, $sum - $v);
                }   
        }   
        return $ret;
}
echo proRand($pro);
Copy after login

More complex ones may add weights to the probability.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to read large excel file data with PHP

The above is the detailed content of Introduction to PHP random probability calculation function. For more information, please follow other related articles on 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