All Projects β†’ bpolaszek β†’ Cartesian Product

bpolaszek / Cartesian Product

Licence: mit
PHP - A simple, low-memory footprint function to generate all combinations from a multi-dimensionnal array.

Projects that are alternatives of or similar to Cartesian Product

utils.js
πŸ‘· πŸ”§ zero dependencies vanilla JavaScript utils.
Stars: ✭ 14 (-75.86%)
Mutual labels:  array, function
prototyped.js
Some common Typescript prototypes
Stars: ✭ 22 (-62.07%)
Mutual labels:  array, function
Pim Community Dev
[Community Development Repository] The open source Product Information Management (PIM)
Stars: ✭ 774 (+1234.48%)
Mutual labels:  product
Array Unique
Return an array free of duplicate values. Very fast implementation.
Stars: ✭ 51 (-12.07%)
Mutual labels:  array
Cracking The Coding Interview
Solutions for Cracking the Coding Interview - 6th Edition
Stars: ✭ 35 (-39.66%)
Mutual labels:  array
Array First
Get the first element or first n elements of an array.
Stars: ✭ 6 (-89.66%)
Mutual labels:  array
Href Counter
Golang multi-stage build to count links within a page for SEO
Stars: ✭ 42 (-27.59%)
Mutual labels:  function
Recipe
Collection of PHP Functions
Stars: ✭ 666 (+1048.28%)
Mutual labels:  function
Zarr.js
Javascript implementation of Zarr
Stars: ✭ 54 (-6.9%)
Mutual labels:  array
Kakajson
Fast conversion between JSON and model in Swift.
Stars: ✭ 867 (+1394.83%)
Mutual labels:  array
Golang Combinations
Golang library which provide an algorithm to generate all combinations out of a given string array.
Stars: ✭ 51 (-12.07%)
Mutual labels:  array
Webify
Turn shell commands into web services
Stars: ✭ 852 (+1368.97%)
Mutual labels:  function
Generate Random Web V7.19.03
Projeto para um cliente, afim de automatizar a escolha de nΓΊmeros, pois o mesmo Γ© jogador de loterias e queria um sistema para gerar jogos prontos.
Stars: ✭ 19 (-67.24%)
Mutual labels:  array
Sma
Calculate the simple moving average of an array.
Stars: ✭ 48 (-17.24%)
Mutual labels:  array
Pyopencl
OpenCL integration for Python, plus shiny features
Stars: ✭ 790 (+1262.07%)
Mutual labels:  array
Gormt
database to golang struct
Stars: ✭ 1,063 (+1732.76%)
Mutual labels:  function
Array To Xml
A simple class to convert an array to xml
Stars: ✭ 744 (+1182.76%)
Mutual labels:  array
Shallow Clone
Make a shallow clone of an object, array or primitive.
Stars: ✭ 23 (-60.34%)
Mutual labels:  array
Sharpmath
A small .NET math library.
Stars: ✭ 36 (-37.93%)
Mutual labels:  function
Immutable Array Prototype
A collection of Immutable Array prototype methods(Per method packages).
Stars: ✭ 56 (-3.45%)
Mutual labels:  array

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Cartesian Product

A simple, low-memory footprint function to generate all combinations from a multi-dimensionnal array.

Usage

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

use function BenTools\CartesianProduct\cartesian_product;

$data = [
    'hair' => [
        'blond',
        'black'
    ],
    'eyes' => [
        'blue',
        'green',
        function (array $combination) { // You can use closures to dynamically generate possibilities
            if ('black' === $combination['hair']) { // Then you have access to the current combination being built
                return 'brown';
            }
            return 'grey';
        }
    ]
];

foreach (cartesian_product($data) as $combination) {
    printf('Hair: %s - Eyes: %s' . PHP_EOL, $combination['hair'], $combination['eyes']);
}

Output:

Hair: blond - Eyes: blue
Hair: blond - Eyes: green
Hair: blond - Eyes: grey
Hair: black - Eyes: blue
Hair: black - Eyes: green
Hair: black - Eyes: brown

Array output

Instead of using foreach you can dump all possibilities into an array.

print_r(cartesian_product($data)->asArray());

Output:

Array
(
    [0] => Array
        (
            [hair] => blond
            [eyes] => blue
        )

    [1] => Array
        (
            [hair] => blond
            [eyes] => green
        )

    [2] => Array
        (
            [hair] => blond
            [eyes] => grey
        )

    [3] => Array
        (
            [hair] => black
            [eyes] => blue
        )

    [4] => Array
        (
            [hair] => black
            [eyes] => green
        )

    [5] => Array
        (
            [hair] => black
            [eyes] => brown
        )

)

Combinations count

You can simply count how many combinations your data produce:

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

use function BenTools\CartesianProduct\cartesian_product;

$data = [
    'hair' => [
        'blond',
        'red',
    ],
    'eyes' => [
        'blue',
        'green',
        'brown',
    ],
    'gender' => [
        'male',
        'female',
    ]
];
var_dump(count(cartesian_product($data))); // 2 * 3 * 2 = 12

Installation

PHP 5.6+ is required.

composer require bentools/cartesian-product

Performance test

The following example was executed on my Core i7 personnal computer with 8GB RAM.

require_once __DIR__ . '/vendor/autoload.php';
use function BenTools\CartesianProduct\cartesian_product;

$data = array_fill(0, 10, array_fill(0, 5, 'foo'));

$start = microtime(true);
foreach (cartesian_product($data) as $c => $combination) {
    continue;
}
$end = microtime(true);

printf(
    'Generated %d combinations in %ss - Memory usage: %sMB / Peak usage: %sMB',
    ++$c,
    round($end - $start, 3),
    round(memory_get_usage() / 1024 / 1024),
    round(memory_get_peak_usage() / 1024 / 1024)
);

Output:

Generated 9765625 combinations in 1.61s - Memory usage: 0MB / Peak usage: 1MB

Unit tests

./vendor/bin/phpunit

Other implementations

th3n3rd/cartesian-product

patchranger/cartesian-iterator

Benchmark

See also

bentools/string-combinations

bentools/iterable-functions

Credits

Titus on StackOverflow - you really rock.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].