mschandr/weighted-random 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mschandr/weighted-random

Composer 安装命令:

composer require mschandr/weighted-random

包简介

Library for generating a weighted random sample

README 文档

README

PHPUnit Tests codecov Latest Stable Version License

This library is used to pick random values from a set of registered values, where values with a higher weight have a larger probability to be picked.

Installation

To install this library using Composer:

composer require mschandr/weighted-random

📚 Documentation

🚀 Usage

Basic Usage

use mschandr\WeightedRandom\WeightedRandom;

// Create a generator
$gen = WeightedRandom::createFloat();

// Register values with weights
$gen->registerValue('common', 7.0)
    ->registerValue('uncommon', 2.5)
    ->registerValue('rare', 0.5);

// Generate a random value
$result = $gen->generate();

// Generate multiple values
$results = $gen->generateMultiple(10);

// Generate unique values (no duplicates)
$unique = $gen->generateMultipleWithoutDuplicates(3);

Batch Registration

$gen->registerValues([
    'apple'  => 3.0,
    'banana' => 2.0,
    'cherry' => 1.0,
]);

Groups (Multiple Values, Single Weight)

// Register a group of values that share a single weight
$gen->registerGroup(['bronze', 'silver', 'gold'], 5.0);
// When the group is selected, one member is chosen uniformly at random

Fair Distribution (Bag System)

$bag = WeightedRandom::createBag();
$bag->registerValues(['rare' => 1, 'common' => 9]);

// Over 10 draws: exactly 1 rare, 9 common (then bag reshuffles)
$results = $bag->generateMultiple(10);

Distribution Introspection

// Get probability distribution
$distribution = $gen->getDistribution();
// Returns: ['apple' => 0.5, 'banana' => 0.333, 'cherry' => 0.167]

// Get probability of specific value
$prob = $gen->getProbability('apple'); // 0.5

// Calculate Shannon entropy (distribution randomness)
$entropy = $gen->getEntropy();

// For numeric values - statistical analysis
$gen->registerValues([1 => 1.0, 2 => 2.0, 3 => 1.0]);
$mean = $gen->getExpectedValue();      // Weighted mean
$variance = $gen->getVariance();       // Weighted variance
$stdDev = $gen->getStandardDeviation(); // Standard deviation

Decay/Boost (Dynamic Weight Adjustment)

// Manual weight adjustment
$gen->decayWeight('common', 0.8);  // Reduce weight to 80%
$gen->boostWeight('rare', 1.5);    // Increase weight by 50%

// Adjust all weights
$gen->decayAllWeights(0.9);  // Reduce all weights to 90%
$gen->boostAllWeights(1.2);  // Increase all weights by 20%

// Automatic adjustment based on selection frequency
$gen->enableSelectionTracking();

// Generate some values...
$gen->generateMultiple(100);

// Auto-adjust: frequently selected values get decayed, rare ones get boosted
$gen->autoAdjustWeights(0.5); // 0.5 = adjustment strength

// View selection counts
$counts = $gen->getSelectionCounts();

// Reset tracking
$gen->resetSelectionCounts();

Composite Generators (Nested/Hierarchical)

// Create a hierarchy of generators
$rareLoot = WeightedRandom::createFloat();
$rareLoot->registerValues(['legendary_sword' => 1.0, 'magic_ring' => 1.0]);

$commonLoot = WeightedRandom::createFloat();
$commonLoot->registerValues(['wooden_sword' => 3.0, 'bread' => 2.0]);

$lootBox = WeightedRandom::createFloat();
$lootBox->registerValue($rareLoot, 0.1);    // 10% chance of rare loot table
$lootBox->registerValue($commonLoot, 0.9);  // 90% chance of common loot table

$item = $lootBox->generate(); // Draws from nested generator

Requirements

  • PHP 8.1 – 8.4
  • Composer Seeded RNG requires PHP 8.2+. On PHP 8.1, those tests are automatically skipped.

🛠 Development

vendor/bin/phpunit -c phpunit.xml --color

GitHub Actions CI runs tests against PHP 8.1, 8.2, 8.3, 8.4.

License

MIT License.

Migration Guide (2.x → 3.x)

WeightedRandom 2.x introduces new features and stricter validation. If you’re upgrading from 1.x, here’s what you need to know:

What’s New

  • Float weight support → Use 0.7 vs 0.3 without scaling up to integers.
  • Seeded RNG with namespace isolation (PHP ≥ 8.2) → Deterministic, reproducible draws.
  • Chaining API for cleaner code.
  • Probability helpers:
    • normalizeWeights() → normalized distribution.
    • getProbability($value) → single-value probability.
  • Bag System (v2.2+) → fairness via without-replacement draws.
  • Stricter validation → safer, more predictable behavior.

Roadmap

  1. Floats + Normalization
  2. Validation Enhancements
  3. Chaining API
  4. Groups
  5. Seeded RNG
  6. Distribution Introspection
  7. Bag System
  8. Decay/Boost
  9. Composite Generators
  10. Code coverage and proper testing

mschandr/weighted-random 适用场景与选型建议

mschandr/weighted-random 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「random」 「weighted」 「sampling」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mschandr/weighted-random 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mschandr/weighted-random 我们能提供哪些服务?
定制开发 / 二次开发

基于 mschandr/weighted-random 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 20
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-06