I’ve the following list, and I want to find all the combinations of
its sub-lists that meet specific conditions, as represented below:
This is the original list:
In[77]:= pk={{2, 3, 1}, {6, 3, 2}, {18, 3, 3}, {4, 5, 1}, {20, 5, 2}, {6, 7,
1}, {10, 11, 1}, {12, 13, 1}, {16, 17, 1}, {18, 19, 1}};
I want to find all the combinations of sub-lists with the sum of
whose first elements equal to the following value:
n=22;
Create the combinations with all possible lengths:
sub=Subsets[pk,{2,Length[pk]}];
This is the result list, which in addition meets the following condition:
All the second elements in a specific sub-list should be different.
lst=Select[ sub, (#[[All,1]]//Total)==n && (#[[All,2]]//Length)==(Union[ #[[All,2]] ]//Length) & ]
Out[80]= {{{2, 3, 1}, {20, 5, 2}}, {{6, 3, 2}, {16, 17, 1}}, {{18, 3,
3}, {4, 5, 1}}, {{4, 5, 1}, {18, 19, 1}}, {{6, 7, 1}, {16, 17,
1}}, {{10, 11, 1}, {12, 13, 1}}, {{2, 3, 1}, {4, 5, 1}, {16, 17,
1}}, {{6, 3, 2}, {4, 5, 1}, {12, 13, 1}}, {{6, 3, 2}, {6, 7,
1}, {10, 11, 1}}, {{4, 5, 1}, {6, 7, 1}, {12, 13, 1}}, {{2, 3,
1}, {4, 5, 1}, {6, 7, 1}, {10, 11, 1}}}
Here’s my difficulty: when the initial list pk is longer than 20, the above
algorithm will be very time-consuming. So, I must seek a more
efficient method to solve this problem. Any tips will be appreciated.
Regards,
Zhao