PDA

View Full Version : Generating a matrix of combinations from arrays


Jak-S
07-21-2006, 05:09 PM
Hi,

Can anyone help me out with this, I can’t get my head round it.

I have an array, it can have any number of elements, and each element contains another array which can also contain any number of elements, here is an example array:

array(6) {
[0]=>
array(1) {
[0]=>
string(1) "6"
}
[1]=>
array(1) {
[0]=>
string(2) "19"
}
[2]=>
array(1) {
[0]=>
string(2) "23"
}
[3]=>
array(1) {
[0]=>
string(2) "38"
}
[4]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "9"
[3]=>
string(2) "10"
}
[5]=>
array(4) {
[0]=>
string(1) "3"
[1]=>
string(2) "11"
[2]=>
string(2) "14"
[3]=>
string(2) "17"
}
}

What I need to do is write some sort of recursive script that can generate an array of every single possible combination of the elements in the child arrays, so something like this:

6, 19, 23, 38, 1, 3
6, 19, 23, 38, 1, 11
6, 19, 23, 38, 1, 14
6, 19, 23, 38, 1, 14
6, 19, 23, 38, 2, 3
6, 19, 23, 38, 2, 11
6, 19, 23, 38, 2, 14
6, 19, 23, 38, 2, 14
6, 19, 23, 38, 9, 3
6, 19, 23, 38, 9, 11
etc…..

I don’t need the same sets of numbers in different orders, just the unique combinations. The output would again be an array with child arrays, one element in the main array for each combination, and then the child arrays will have an element for each separate number.

If anyone can help me out that would be great. Thanks,

Jack

marek_mar
07-22-2006, 12:56 AM
It's not recursive... but it should do what you want anyway.

<?php
$array = array(
array(6),
array(19),
array(23),
array(38),
array(
1,
2,
9,
10
),
array(
3,
11,
14,
17
)
);
print '<pre>';
var_dump(do_something_weird($array));

function do_something_weird(array $data)
{
// Let's see... number of combinations should be this...
$number_of_combinations = 1;
$sizes = array();
for($i = 0, $n = count($data); $i < $n; ++$i)
{
$number_of_combinations *= $sizes[] = count($data[$i]);
}
$combinations = array();
$modulo = $number_of_combinations;
for($j = 0; $j < $n; ++$j)
{
$modulo = $modulo / $sizes[$j];
$k = 0;
for($i = 0; $i < $number_of_combinations; ++$i)
{
$combinations[$i][$j] = $data[$j][$k % $sizes[$j]];
if(!(($i + 1) % $modulo))
{
$k++;
}
}
}
return $combinations;
}
?>

Jak-S
07-24-2006, 09:10 AM
marek_mar: THANK YOU!
Thats fantastic, i really just couldnt get my head round it, much appreciated.

marek_mar
07-24-2006, 03:38 PM
You know where the thank you (http://www.codingforums.com/showthread.php?p=467650) thread is... :D

Jak-S
07-24-2006, 05:11 PM
You know where the thank you (http://www.codingforums.com/showthread.php?p=467650) thread is... :D

No Probs :D