I have a list of 21 elements from which I have obtained possible combinations of minimum 3 and up to 10 elements using the Subsets
function as follows:
Elements=RandomReal[1, 21];
Combinations=Subsets[Elements,{3,10}];
For simplicity's sake I have made the list of elements in this example a vector of 21 random reals. In reality, each element in my list is in itself a vector of length = ~60.
The elements in my list belong to 3 separate groups, and I need to ensure that the combinations contain at least one element from each group. I have done this in the following manner:
Group1 = Elements[[1 ;; 7]];
Group2 = Elements[[8 ;; 14]];
Group3 = Elements[[15 ;; 21]];
NewCombinations = {};
i = 1;
For[i = 1, i <= Length[Combinations], i++,
If[ContainsAny[Combinations[[i]], Group1] &&
ContainsAny[Combinations[[i]], Group2] &&
ContainsAny[Combinations[[i]], Group3],
AppendTo[NewCombinations, Combinations[[i]]]
];
];
However, because the total possible number of subsets from 3 to 10 elements of a list of 21 elements (i.e. Length[Combinations]
) is 1,048,344, and this way of creating new combinations includes a For
cycle with 3 nested If
cycles, the evaluation is taking forever.
Is there a way of simplifying or optimising the subroutine that calculates 'NewCombinations' to make it faster?
Thank you very much in advance!