Introduction to PHP random probability calculation function

不言
Release: 2023-04-03 06:24:01
Original
2339 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

10, 'b' =>20, 'c' =>30, 'd' =>40 ]; function proRand($pro) { $ret = ''; $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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!