SO,
The problem
From SQL I'm getting an array with strings (flat array) - let it be
$rgData = ['foo', 'bar', 'baz', 'bee', 'feo'];
Now, I want to get possible combinations of pairs and triplets of this array (and, in common case, combinations of 4 elements e t.c.). To be more specific: I mean combinations in math sense (without duplicates), i.e. those, which count is equal to
-so for array above that will be 10 for both pairs and triplets.
My approach
I've started from mapping possible values for to possible array selected items. My current solution is to point if an element is selected as "1", and "0" otherwise. For sample above that will be:
foo bar baz bee feo 0 0 1 1 1 -> [baz, bee, feo] 0 1 0 1 1 -> [bar, bee, feo] 0 1 1 0 1 -> [bar, baz, feo] 0 1 1 1 0 -> [bar, baz, bee] 1 0 0 1 1 -> [foo, bee, feo] 1 0 1 0 1 -> [foo, baz, feo] 1 0 1 1 0 -> [foo, baz, bee] 1 1 0 0 1 -> [foo, baz, feo] 1 1 0 1 0 -> [foo, bar, bee] 1 1 1 0 0 -> [foo, bar, baz]
And all I need to do is somehow produce desired bit set. Here's my code in PHP:
function nextAssoc($sAssoc)
{
if(false !== ($iPos = strrpos($sAssoc, '01')))
{
$sAssoc[$iPos] = '1';
$sAssoc[$iPos+1] = '0';
return substr($sAssoc, 0, $iPos+2).
str_repeat('0', substr_count(substr($sAssoc, $iPos+2), '0')).
str_repeat('1', substr_count(substr($sAssoc, $iPos+2), '1'));
}
return false;
}
function getAssoc(array $rgData, $iCount=2)
{
if(count($rgData)<$iCount)
{
return null;
}
$sAssoc = str_repeat('0', count($rgData)-$iCount).str_repeat('1', $iCount);
$rgResult = [];
do
{
$rgResult[]=array_intersect_key($rgData, array_filter(str_split($sAssoc)));
}
while($sAssoc=nextAssoc($sAssoc));
return $rgResult;
}
-I've chosen to store my bits as a normal string. My algorithm for producing next association is:
- Try to find "01". If not found, then it's 11..100..0 case (so it's maximum, no more could be found). If found, go to second step
- Go to most right position of "01" in string. Switch it to "10" and then move all zeros that are righter than found "01" position - to left.
For example,
01110
: the most right position of "01" is 0, so first we switch this "01" to "10". String now sill be10110
. Now, go to right part (it's without10
part, so it starts from 0+2=2-nd symbol), and move all zeros to left, i.e.110
will be011
. As result, we have10
+011
=10111
as next association for01110
.
I've found similar problem here - but there OP wants combinations with duplicates, while I want them without duplicated.
The question
My question is about two points:
- For my solution, may be there's another way to produce next bit set more efficient?
- May be there are more simple solutions for this? It seems to be standard problem.