PHPackages                             mschandr/weighted-random - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mschandr/weighted-random

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mschandr/weighted-random
========================

Library for generating a weighted random sample

v3.0.0-stable(4mo ago)10MITPHPPHP ^8.2 || ^8.3 || ^8.4CI passing

Since Jun 14Pushed 4mo agoCompare

[ Source](https://github.com/mschandr/weighted-random)[ Packagist](https://packagist.org/packages/mschandr/weighted-random)[ RSS](/packages/mschandr-weighted-random/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (6)Versions (8)Used By (0)

Weighted Random
===============

[](#weighted-random)

[![PHPUnit Tests](https://github.com/mschandr/weighted-random/actions/workflows/php.yml/badge.svg)](https://github.com/mschandr/weighted-random/actions/workflows/php.yml)[![codecov](https://camo.githubusercontent.com/dc825e58e105ccf0fdd2337db50c85ca3b0e5021ade4d0ba97ae701d451f25ff/68747470733a2f2f636f6465636f762e696f2f6769746875622f6d736368616e64722f77656967687465642d72616e646f6d2f67726170682f62616467652e7376673f746f6b656e3d344a373044485946544b)](https://codecov.io/github/mschandr/weighted-random)[![Latest Stable Version](https://camo.githubusercontent.com/62bbb9266c93d95d1cf9f7fa7b6485723f9cba36fe192a9785d4bdaa1d881047/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d736368616e64722f77656967687465642d72616e646f6d2e737667)](https://packagist.org/packages/mschandr/weighted-random)[![License](https://camo.githubusercontent.com/f8a13f72b6468136017a1c41969810f8f84cc6503307a04e2aa87d48537fd178/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d736368616e64722f77656967687465642d72616e646f6d2e737667)](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
------------

[](#installation)

To install this library using Composer:

```
composer require mschandr/weighted-random
```

📚 Documentation
---------------

[](#-documentation)

- **[API Reference](API.md)** - Complete API documentation for all classes and methods
- **[CHANGELOG](CHANGELOG.md)** - Version history and migration guides
- **[Contributing Guide](CONTRIBUTING.md)** - Guidelines for contributing to the project

🚀 Usage
-------

[](#-usage)

### Basic 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

[](#batch-registration)

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

### Groups (Multiple Values, Single Weight)

[](#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)

[](#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

[](#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)

[](#decayboost-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)

[](#composite-generators-nestedhierarchical)

```
// 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
------------

[](#requirements)

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

🛠 Development
-------------

[](#-development)

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

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

License
-------

[](#license)

MIT License.

---

Migration Guide (2.x → 3.x)
---------------------------

[](#migration-guide-2x--3x)

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
----------

[](#whats-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
=======

[](#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

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance74

Regular maintenance activity

Popularity2

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 87.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~112 days

Recently: every ~28 days

Total

6

Last Release

143d ago

Major Versions

1.3 → 2.0.0-stable2025-09-10

v2.2.0.x-dev → v3.0.0-stable2025-12-27

PHP version history (4 changes)1.1PHP ^8.3

1.3PHP ^8.2

v2.2.0-stablePHP ^8.1 || ^8.2 || ^8.3 || ^8.4

v3.0.0-stablePHP ^8.2 || ^8.3 || ^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/be447f5fd1f8d777007695415e7dc783b7302ac47f4f1f7f3a3f4ed71a53b65e?d=identicon)[mschandr](/maintainers/mschandr)

---

Top Contributors

[![mschandr](https://avatars.githubusercontent.com/u/1372966?v=4)](https://github.com/mschandr "mschandr (34 commits)")[![mdhas-appno](https://avatars.githubusercontent.com/u/73550489?v=4)](https://github.com/mdhas-appno "mdhas-appno (3 commits)")[![FrankHouweling](https://avatars.githubusercontent.com/u/1426973?v=4)](https://github.com/FrankHouweling "FrankHouweling (2 commits)")

---

Tags

randomphpweightedsampling

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mschandr-weighted-random/health.svg)

```
[![Health](https://phpackages.com/badges/mschandr-weighted-random/health.svg)](https://phpackages.com/packages/mschandr-weighted-random)
```

###  Alternatives

[ihor/nspl

Non-standard PHP library (NSPL) - functional primitives toolbox and more

381368.5k](/packages/ihor-nspl)[gladcodes/keygen

A fluent PHP random key generator.

119668.9k2](/packages/gladcodes-keygen)[savvot/random

Deterministic pseudo-random generators library with dozens of useful functions and several sources of randomness

21243.7k5](/packages/savvot-random)[orangesoft/throttler

Load balancer between nodes.

1732.3k1](/packages/orangesoft-throttler)[sinergi/token

PHP library to generate random strings

188.7k9](/packages/sinergi-token)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
