anarchitecture/combinatorics
最新稳定版本:v0.1.3
Composer 安装命令:
composer require anarchitecture/combinatorics
包简介
Combinatorics helpers for functional pipelines (powerset, permutations, allocations) for PHP 8.5+.
README 文档
README
Combinatorics helpers for functional pipelines in PHP 8.5+, designed to pair nicely with the pipe operator (|>) and the anarchitecture/pipe library.
This package intentionally focuses on search-space helpers (often exponential). Keep your core FP primitives in a smaller library, and pull these in when you need them.
Install
composer require anarchitecture/combinatorics
Usage
<?php use Anarchitecture\combinatorics as c; use Anarchitecture\pipe as p; $items = ['a' => 1, 'b' => 2]; $subsets = $items |> c\iterable_powerset() |> p\collect(...) // [ // [], // ['a'=>1], // ['b'=>2], // ['a'=>1,'b'=>2] // ]
Functions
iterable_combinations(int $n)
Yield all subsets of exactly size $n from an iterable. Output is lazy; input is materialized into an array first.
- Preserves the original keys in each subset.
- Yields
C(count(items), n)combinations (binomial coefficient). - For
$n = 0, yields the empty subset only:[[]]. - Throws
InvalidArgumentExceptionif$n < 0.
use Anarchitecture\combinatorics as c; use Anarchitecture\pipe as p; $items = ['a' => 1, 'b' => 2, 'c' => 3]; $pairs = $items |> c\iterable_combinations(2) |> p\collect(...); // [ // ['b' => 2, 'c' => 3], // ['a' => 1, 'c' => 3], // ['a' => 1, 'b' => 2], // ]
iterable_powerset()
Yield all subsets (the power set) of an iterable. Output is lazy; input is materialized into an array first.
- Yields 2^n subsets, including the empty subset
[]. - Preserves the original keys in each subset.
iterable_permutations()
Yield all permutations of an iterable (materialized into an array). Output is lazy.
- Yields n! permutations.
- Preserves keys (keys stay attached to values; order changes).
iterable_allocations(int $total)
Given a list of items (keys), yield all allocations of a non-negative integer total across those keys.
- Each yielded allocation is an array keyed by the input keys, with non-negative integer values summing to
$total. - Yields
C(total + n - 1, n - 1)allocations (n = number of items).
Generate all non-negative integer allocations that sum to a fixed total.
use Anarchitecture\combinatorics as c; use Anarchitecture\pipe as p; $allocations = ['a' => null, 'b' => null, 'c' => null] |> c\iterable_allocations(2) |> p\collect(...); // [ // ['a' => 0, 'b' => 0, 'c' => 2], // ['a' => 0, 'b' => 1, 'c' => 1], // ['a' => 0, 'b' => 2, 'c' => 0], // ['a' => 1, 'b' => 0, 'c' => 1], // ['a' => 1, 'b' => 1, 'c' => 0], // ['a' => 2, 'b' => 0, 'c' => 0], // ]
License
MIT
统计信息
- 总下载量: 4
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 5
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-15