This article mainly introduces the PHP probabilistic random lottery case. Interested friends can refer to it. I hope it will be helpful to everyone.
1. Initial data:
The greater the weight, the higher the probability of drawing
[Prize 1, Weight 5], [Prize 2, Weight 6], [Prize 3, weight 7], [prize 4, weight 2]
2. Processing steps:
1) N = 5 6 7 2 = 20
2) Then take 1-N random number M
3) Define the weight range value of each prize Prize 1: 1-5; Prize 2: 6-11; Prize 3: 12-18; Prize 4: 19-20
4 ) If M is within the weight range of a certain prize, it indicates that the prize was drawn to
<?php /** * 奖品 */ class Prize { # ID public $id = null; # 权重 public $weight = null; # 奖品名 public $name = null; # 权重范围区间起始值 protected $start = 0; # 权重范围区间结束值 protected $end = 0; public function __construct($id, $weight, $name) { if (!$id) { throw new Exception('奖品ID为空.'); } $this->id = $id; $this->weight = $weight ? $weight : 0; $this->name = $name ? $name : '随机奖品' . $id; } # id public function getId() { return $this->id; } # 权重 public function getWeight() { return $this->weight; } # 设置权重范围区间 public function setRange($start, $end) { $this->start = $start; $this->end = $end; } # 判断随机数是否在权重范围区间 public function inRange($num) { return ($num >= $this->start) && ($num <= $this->end); } } /** * 奖品池 */ class PrizePoll implements IteratorAggregate, Countable { # 奖品集 protected $items = array(); # 加入奖品 public function addItem(Prize $item) { $this->items[$item->getId()] = $item; return $this; } # 删除奖品 public function removeItem($itemId) { if (isset($this->items[$itemId])) { unset($this->items[$itemId]); } return $this; } # 更新奖品 public function updateItem(Prize $item) { if (isset($this->items[$item->getId()])) { $this->items[$item->getId()] = $item; } return $this; } # 获取所有奖品 public function getItems() { return $this->items; } # 所有所有可用奖品(如果权重为0,说明这个奖品永远不可能抽到) public function getVisibleItems() { $items = array(); foreach ($this->items as $item) { if ($item->getWeight()) { $items[$item->getId()] = $item; } } return $items; } # Countable::count public function count() { return count($this->items); } # IteratorAggregate::getIterator() public function getIterator() { return new ArrayIterator($this->items); } } /** * 简单的抽奖类 */ class SimpleTurn { # 奖池 protected $poll = null; public function __construct(PrizePoll $poll) { if ($poll) { $this->setPoll($poll); } } # 抽奖 public function run(PrizePoll $poll) { $poll = $poll ? $poll : $this->poll; if ( ! $poll) { throw new Exception('奖池未初始化'); } if ($poll->count() <= 0) { throw new Exception('奖池为空'); } $items = $poll->getVisibleItems(); if (count($items) <= 0) { throw new Exception('奖池为空'); } $sum = 0; foreach ($items as $item) { $start = $sum + 1; $sum += $item->getWeight(); $end = $sum; # 设置奖品的权重范围区间 $item->setRange($start, $end); } # 随机数 $rand = $this->getRandNum(1, $sum); # 区间段判断 foreach ($items as $item) { if ($item->inRange($rand)) { return $item; } } return null; } # 获取随机数 public function getRandNum($min, $max) { return mt_rand($min ? $min : 1, $max); } # 设置奖池 public function setPoll(PrizePoll $poll) { $this->poll = $poll; } } # 示例 try { $prizePoll = new PrizePoll(); $prizePoll->addItem(new Prize(1, 5)) ->addItem(new Prize(2, 6)) ->addItem(new Prize(3, 7)) ->addItem(new Prize(4, 2)); $turn = new SimpleTurn($prizePoll); $prize = $turn->run(); var_dump($prize); } catch (Exception $e) { print_r($e); }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Summary of the use of PHP’s openssl encryption extension
Detailed explanation of 301 redirection examples based on PHP
##Analysis of capturing groups and non-capturing groups in PHP regular expressions
##
The above is the detailed content of PHP probabilistic random lottery case. For more information, please follow other related articles on the PHP Chinese website!

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use
