Home > Backend Development > PHP Tutorial > PHP lottery program and random advertising implementation algorithm

PHP lottery program and random advertising implementation algorithm

WBOY
Release: 2016-07-25 08:53:34
Original
1424 people have browsed it
  1. /**
  2. * Full probability calculation
  3. *
  4. * @param array $p array('a'=>0.5,'b'=>0.2,'c'=>0.4)
  5. * @return string Returns the key of the above array
  6. */
  7. function random($ps){
  8. static $arr = array();
  9. $key = md5(serialize($ps));
  10. if (!isset($arr[$key])) {
  11. $max = array_sum($ps);
  12. foreach ($ps as $k=>$v) {
  13. $v = $v / $max * 10000;
  14. for ($i=0; $i<$v; $i++) $arr[$key][] = $k;
  15. }
  16. }
  17. return $arr[$key][mt_rand(0,count($arr [$key])-1)];
  18. }
Copy code

Example 2, PHP lottery program algorithm 2

  1. function get_rand($proArr) {
  2. $result = '';
  3. //Total probability accuracy of probability array
  4. $proSum = array_sum($proArr);
  5. //Probability array loop
  6. foreach ($proArr as $key => $proCur) {
  7. $randNum = mt_rand(1, $proSum);
  8. if ($randNum <= $proCur) {
  9. $result = $key;
  10. break;
  11. } else {
  12. $proSum -= $proCur;
  13. }
  14. }
  15. unset ($proArr);
  16. return $result;
  17. }
Copy code

The above code is a classic probability algorithm, $proArr is a The preset array, assuming the array is: array(100,200,300,400), starts by screening the first number from the probability range of 1,1000 to see if it is within its occurrence probability range. If not, the probability is reduced. That is, the probability space is the value of k minus the number just now. In this case, it is minus 100. That is to say, the second number is filtered within the range of 1,900. In this way, until the end, there will always be a number that meets the requirements. It's like touching something in a box. If the first one isn't right, the second one isn't right, and the third one isn't right, then the last one must be.

This algorithm is simple and very efficient. The key is that this algorithm has been applied in previous projects, especially in projects with large amounts of data. The efficiency is very good.



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