Ergun
Ergun

Reputation: 520

Getting all possible combinations of 2 lists

I have 2 lists:

I have to calculate all possible combinations using all the elements of the 2 arrays:

And so on. The length of the lists is dynamic. How do I write the function in PHP necessary to solve this problem?

Upvotes: 0

Views: 913

Answers (3)

Cal
Cal

Reputation: 7157

A simple nested loop works:

$sets = array();
foreach ($list1 as $elm1){
    foreach ($list2 as $elm2){
        $sets[] = array($elm1, $elm2);
    }
}

If you need the null versions too, pad the arrays first:

$max = max(count($list1), count($list2));
$list1 = array_pad($list1, $max, null);
$list2 = array_pad($list2, $max, null);

Upvotes: 1

msigman
msigman

Reputation: 4524

This is called "cartesian product", php man page on arrays http://php.net/manual/en/ref.array.php shows some implementations (in comments).

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

Example:

$cross = array_cartesian(
    array('apples', 'pears',  'oranges'),
    array('steve', 'bob')
);

To see the output:

print_r($cross);

Upvotes: 0

kasavbere
kasavbere

Reputation: 6003

1 -- get all permutations of list1 as X, the longer list

2-- for each element in X, create a mapping on list2

3 -- time complexity: X*list2

Upvotes: 0

Related Questions