I have the following array containing arrays of values:
$array = array( array('1', '2'), array('a', 'b', 'c'), array('x', 'y'), );
There can be any number of arrays, and an array can contain any number of values. Currently, I have a piece of code that will generate all combinations where one value is taken from each array. eg:
1ax, 1ay, 1bx, 1by, 1cx, 1cy, 2ax, 2ay, 2bx, 2by, 2cx, 2cy
However, what I really want is only combinations in which only one value is in each column, i.e. 1ax is not good because all three values ββ1, a and x are in the first column, 1by is not good because b and y are in the second column. Therefore, from the above example, there will only be the following combinations:
1cy, 2cx
I initially planned to just generate all the combinations, and then filter out those with conflicts, but this does not scale, since this is a simplified example, in a real application there will be situations where there are potentially millions of combinations (including conflicting ones).
Can someone help with a better way to solve this problem? I work in PHP, but any code sample that demonstrates the logic will be useful.
Thanks in advance.
Update:
I tested solutions that work against a larger dataset to get some benchmarks, these are the results so far:
$array = array( array('1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3'), array('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'), array('x', 'y', 'z', 'x', 'y', 'z', 'x', 'y', 'z'), array('1', '2', '3', '1', '2', '3', '1', '2', '3'), array('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'), array('x', 'y', 'z'), );
Josh Davis 2nd Solution:
Combinations: 249480 Time: 0.3180251121521 secs Memory Usage: 22.012168884277 mb Peak Memory Usage: 22.03059387207 mb
Josh Davis:
Combinations: 249480 Time: 1.1172790527344 secs Memory Usage: 22.004837036133 mb Peak Memory Usage: 22.017387390137 mb
Tom Hay:
Combinations: 249480 Time: 5.7098741531372 secs Memory Usage: 39.145843505859 mb Peak Memory Usage: 39.145843505859 mb