bentools/picker

Helps you pick a random item with weight management.

2.1 2022-10-05 13:44 UTC

This package is auto-updated.

Last update: 2024-05-05 17:30:57 UTC


README

Latest Stable Version License Build Status Coverage Status Total Downloads

Picker

This simple library will help you pick a random item through a collection of items (string, objects, ints, whatever), by optionally giving them a weight.

Usage

use BenTools\Picker\Picker;

require_once __DIR__ . '/vendor/autoload.php';

$collection = [
    [
        'foo',
        80,
    ],
    [
        'bar',
        60,
    ],
    [
        'baz',
        5,
    ],
];

$picker = Picker::create();
foreach ($collection as $key => [$value, $weight]) {
    $picker = $picker->withItem($value, $weight);
}

echo $picker->pick(); // Will be mostly foo or bar

Of course you can also simply pick a random value with a simple, no-weighted set:

$picker = Picker::create()->withItems(['foo', 'bar', 'baz']);
echo $picker->pick(); // Will be a truly random value between foo, bar and baz

Shift

The picker can optionally shift items once they're picked:

$picker = Picker::create(shift: true)->withItems(['foo', 'bar']);
$picker->pick(); // let's assume `foo` is picked
$picker->pick(); // only `bar` remains
$picker->pick(); // RuntimeException

Installation

This library requires PHP 7.3+.

composer require bentools/picker

Tests

./vendor/bin/pest

See also

bentools/split-test-analyzer

bentools/cartesian-product

bentools/pager